Results 1 to 19 of 19

Thread: [RESOLVED] Problem with Color.FromName

  1. #1

    Thread Starter
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,500

    Resolved [RESOLVED] Problem with Color.FromName

    Hi,

    I've been trying to use...
    Code:
    Dim myColour As Color = Color.FromName(TextBox1.Text)
    ...to give a user a choice of colour for Form background or, for example, Pen color.

    I've run into a problem because 'Color.FromName' doesn't automatically detect an unknown colour or misspelling, if the text is unknown the code just returns Black.

    Using...
    Code:
         myColour = Color.FromName(TextBox2.Text)
         Me.BackColor = myColour
    ...however does produce a detectable error, and it's what I've been using.

    In a previous thread jmcilhinney made this suggestion:
    Quote Originally Posted by jmcilhinney View Post
    vb.net Code:
    1. Dim names = {"Red", "Rid"}
    2.  
    3. For Each s In names
    4.     If [Enum].IsDefined(GetType(KnownColor), s) Then
    5.         Console.WriteLine($"There is a known colour named '{s}'.")
    6.     Else
    7.         Console.WriteLine($"There is NOT a known colour named '{s}'.")
    8.     End If
    9. Next
    I can see how that would work but I don't really want to sit and add all 140 odd 'Known' colours to the string array 'names', not least because I can't type and produce far too many typo's at the best of times.

    I've been trying, without success, to find where to access a 'look-up' list to compare the text with the known colours. I'm sure there must be a list somewhere in Visual Studio because a selection is presented each time a colour is selected in design.


    Poppa
    Along with the sunshine there has to be a little rain sometime.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: Problem with Color.FromName

    I've been trying, without success, to find where to access a 'look-up' list to compare the text with the known colours.
    Um, the KnownColor enumeration that I just demonstrated for you. You don't have to add anything to any array. You seem to have missed the principle the example was demonstrating. The line that matters there is this one:
    vb.net Code:
    1. If [Enum].IsDefined(GetType(KnownColor), s) Then
    where s is the String value you want to test. In your case, that String value is TextBox1.Text so you substitute that for s, e.g.
    vb.net Code:
    1. Dim colourName = TextBox1.Text
    2.  
    3. If [Enum].IsDefined(GetType(KnownColor), colourName) Then
    4.     Dim colour = Color.FromName(colourName)
    5.  
    6.     'Use colour here.
    7. Else
    8.     'There is no such colour.
    9. End If
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,398

    Re: Problem with Color.FromName

    To elaborate, Enum.IsDefined in this case returns a Boolean value showing whether a value's name exists in the KnownColor enumeration.

    Behind the scenes, it is iterating over every 167 values and checking whether or not the value you passed is one of them.

    Here is the relevant documentation: https://docs.microsoft.com/en-us/dot...enum.isdefined
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  4. #4

    Thread Starter
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,500

    Re: Problem with Color.FromName

    Quote Originally Posted by jmcilhinney View Post
    Um, the KnownColor enumeration that I just demonstrated for you. You don't have to add anything to any array. You seem to have missed the principle the example was demonstrating.

    Sorry John, still got problem. You're right, I did miss what you meant.

    So: this is how I interpreted your post:
    vb.NET Code:
    1. Private Sub Colours()
    2.         Dim colour(2) As Color
    3.  
    4.         colour(0) = Color.FromName(TextBox1.Text)
    5.         colour(1) = Color.FromName(TextBox2.Text)
    6.         For Each s In colour
    7.             If [Enum].IsDefined(GetType(KnownColor), s) Then
    8.                 'Color ok
    9.             Else
    10.                 StartUp()
    11.                 Label3.Show()
    12.             End If
    13.         Next
    14.         pen1 = New Pen(colour(1), 1)
    15.         Me.BackColor = colour(0)
    16.         PictureBox1.BackColor = colour(0)
    17.         PictureBox1.Show()
    18.     End Sub
    When I run this code I get this error at Line 7. (For reference the Line 90 as referenced in the copy below is Line 9 in the shown snippet.)
    System.InvalidOperationException
    HResult=0x80131509
    Message=Unknown enum type.
    Source=mscorlib
    StackTrace:
    at System.RuntimeType.IsEnumDefined(Object value)
    at System.Enum.IsDefined(Type enumType, Object value)
    at Polly_Draw.Form1.Colours() in D:\~VB Trials\Polly Draw\Form1.vb:line 90
    at Polly_Draw.Form1.Button2_Click() in D:\~VB Trials\Polly Draw\Form1.vb:line 68
    at Polly_Draw.Form1._Lambda$__R31-3(Object a0, EventArgs a1)
    at System.Windows.Forms.Control.OnClick(EventArgs e)
    at System.Windows.Forms.Button.OnClick(EventArgs e)
    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
    at System.Windows.Forms.Control.WndProc(Message& m)
    at System.Windows.Forms.ButtonBase.WndProc(Message& m)
    at System.Windows.Forms.Button.WndProc(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
    at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
    at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoCompo nentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
    at Polly_Draw.My.MyApplication.Main(String[] Args) in :line 81

    This exception was originally thrown at this call stack:
    [External Code]
    Polly_Draw.Form1.Colours() in Form1.vb
    Polly_Draw.Form1.Button2_Click() in Form1.vb
    [External Code]
    Which probably means that I've got it wrong again.


    Poppa

    PS.
    Meant to say... This was with two valid colours, 'Red and Blue'.

    Pop.
    Last edited by Poppa Mintin; Sep 25th, 2020 at 11:59 AM.
    Along with the sunshine there has to be a little rain sometime.

  5. #5
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,398

    Re: Problem with Color.FromName

    Do you have System.Drawing imported? I'm able to test JMcIlhinney's solution without any issues:
    Code:
    Imports System
    Imports System.Drawing
    Public Module Module1
        Public Sub Main()
            Dim input As String = Console.ReadLine()
            If [Enum].IsDefined(GetType(KnownColor), input) Then
                Console.WriteLine("{0} is a known color.", input)
            Else
                Console.WriteLine("{0} is not a known color.", input)
            End If
    
        End Sub
    End Module
    Fiddle: Live Demo

    Screenshot:
    Name:  capture.jpg
Views: 1658
Size:  22.2 KB
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  6. #6
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Problem with Color.FromName

    It would help if you had Strict and Explicit on, something you've been told numerous times.

    An experiment / hint

    Code:
            Dim colour(2) As Color
    
            colour(0) = Color.FromName("Blue")
            colour(1) = Color.FromName("red")
            For Each s As String In From c In colour Select c.Name
                If [Enum].IsDefined(GetType(KnownColor), s) Then
                    'Color ok
                    Stop
                Else
                    Stop
                End If
            Next
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  7. #7

    Thread Starter
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,500

    Re: Problem with Color.FromName

    Quote Originally Posted by dbasnett View Post
    It would help if you had Strict and Explicit on, something you've been told numerous times.
    I thought I had both of those 'On' by default but can't find where to check.


    Poppa
    Along with the sunshine there has to be a little rain sometime.

  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Problem with Color.FromName

    You’re doing it wrong...

    Colours(0) = Color.FroName(TextBox1.Text)

    You said yourself in an earlier post that that doesn’t work, so why would it work now?
    You’re supposed to be testing if a STRING color name exists in the knowncolors enum, before setting any colors.fromname

  9. #9

    Thread Starter
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,500

    Re: Problem with Color.FromName

    Update.

    I realised I had a basic error, I was checking a Color, not a String, so I've changed things a bit.
    vb.NET Code:
    1. Private Sub Colours()
    2.         Dim colour(2) As Color, chk(2) As String
    3.  
    4.         '   Ensure the input colours start with an upper case letter.
    5.         chk(0) = TextBox1.Text
    6.         chk(1) = TextBox2.Text
    7.         chk(0) = chk(0).Substring(0, 1).ToUpper & chk(0).Substring(1)
    8.         chk(1) = chk(1).Substring(0, 1).ToUpper & chk(1).Substring(1)
    9.  
    10.         For i = 0 To 1
    11.             If [Enum].IsDefined(GetType(KnownColor), chk(i)) Then
    12.                 colour(i) = Color.FromName(chk(i))
    13.             Else
    14.                 StartUp()
    15.                 Label3.Show()
    16.                 Exit Sub
    17.             End If
    18.         Next
    19.         pen1 = New Pen(colour(1), 1)
    20.         Me.BackColor = colour(0)
    21.         PictureBox1.BackColor = colour(0)
    22.         PictureBox1.Show()
    23.     End Sub
    Well at least my first attempt didn't throw up any errors but it failed to recognise 'red' as a colour.
    Then I tried 'Red' and that worked correctly. So I added Lines 4 to 8.

    Thanks guys


    Poppa
    Along with the sunshine there has to be a little rain sometime.

  10. #10
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: [RESOLVED] Problem with Color.FromName

    Why declare colours(2) and chk(2)???
    You’re only using 2 elements in both. You know arrays are zero based, but you need to declare arrays with the Upperbound and not the Length...

    I.e. colours(1), chk(1)

    Edit: That’s how to declare and dimension an array in VB. In C languages, you do use the array Length when declaring and dimensioning...
    Last edited by .paul.; Sep 25th, 2020 at 07:18 PM.

  11. #11
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: [RESOLVED] Problem with Color.FromName

    If TextBox1.Text = ‘red’ this is how to change it to ‘Red’
    If it already is ‘Red’ and not ‘red’, no harm done...

    Code:
    chk(0) = StrConv(TextBox1.Text, vbProperCase)
    chk(1) = StrConv(TextBox2.Text, vbProperCase)

  12. #12
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: [RESOLVED] Problem with Color.FromName

    As you're using TextBoxes for inputting color names, I'd recommend using AutoComplete to avoid many errors. Here's an example...

    Code:
    Public Class Form1
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim source As New AutoCompleteStringCollection
            source.AddRange([Enum].GetNames(GetType(KnownColor)))
    
            TextBox1.AutoCompleteCustomSource = source
            TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
            TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
    
            TextBox2.AutoCompleteCustomSource = source
            TextBox2.AutoCompleteMode = AutoCompleteMode.SuggestAppend
            TextBox2.AutoCompleteSource = AutoCompleteSource.CustomSource
    
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim c1 As String = TextBox1.Text.ToLower
            Dim c2 As String = TextBox2.Text.ToLower
    
            Dim knownColorNames() As String = [Enum].GetNames(GetType(KnownColor))
            Dim knownColorNamesToLower() As String = [Enum].GetNames(GetType(KnownColor)).Select(Function(n) n.ToLower).ToArray
            Dim i1 As Integer = Array.IndexOf(knownColorNamesToLower, c1)
            Dim i2 As Integer = Array.IndexOf(knownColorNamesToLower, c2)
            If i1 > -1 AndAlso i2 > -1 Then
                c1 = knownColorNames(i1)
                c2 = knownColorNames(i2)
                TextBox1.ForeColor = Color.FromName(c1)
                TextBox1.BackColor = Color.FromName(c2)
                TextBox2.ForeColor = Color.FromName(c2)
                TextBox2.BackColor = Color.FromName(c1)
            End If
        End Sub
    
    End Class

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: [RESOLVED] Problem with Color.FromName

    Keep in mind that the KnownColor enumeration contains values like Red, LightBlue and HighlightText. Here's a method that will match those values regardless of case while also excluding the system values:
    vb.net Code:
    1. Private Function IsColorName(name As String) As Boolean
    2.     Dim knownColorNames = [Enum].GetNames(GetType(KnownColor))
    3.  
    4.     'Check for known colours, e.g. Red, LightBlue, Control.
    5.     If Not knownColorNames.Any(Function(kcn) String.Equals(kcn, name, StringComparison.OrdinalIgnoreCase)) Then
    6.         'The input does not match a known colour.
    7.         Return False
    8.     End If
    9.  
    10.     Dim systemColorNames = GetType(SystemColors).GetProperties(BindingFlags.Public Or BindingFlags.Static).Select(Function(pi) pi.Name)
    11.  
    12.     'Check for system colours, e.g. ButtonFace, Control, HighlightText.
    13.     If systemColorNames.Any(Function(scn) String.Equals(scn, name, StringComparison.OrdinalIgnoreCase)) Then
    14.         'The input matches a system colour.
    15.         Return False
    16.     End If
    17.  
    18.     'The specified colour is known but is not part of the system.
    19.     Return True
    20. End Function
    Sample usage:
    vb.net Code:
    1. Dim colourNames = {"Red", "blue", "Groan", "control", "Window"}
    2.  
    3. For Each colourName As String In colourNames
    4.     Console.WriteLine($"{colourName}: {IsColorName(colourName)}")
    5. Next
    You may also want to allow people to enter values like "light blue". A simple option would be to just remove the spaces from the input before comparing:
    vb.net Code:
    1. Private Function IsColorName(name As String) As Boolean
    2.     name = name.Replace(" ", String.Empty)
    3.  
    4.     Dim knownColorNames = [Enum].GetNames(GetType(KnownColor))
    5.  
    6.     'Check for known colours, e.g. Red, LightBlue, Control.
    7.     If Not knownColorNames.Any(Function(kcn) String.Equals(kcn, name, StringComparison.OrdinalIgnoreCase)) Then
    8.         'The input does not match a known colour.
    9.         Return False
    10.     End If
    11.  
    12.     Dim systemColorNames = GetType(SystemColors).GetProperties(BindingFlags.Public Or BindingFlags.Static).Select(Function(pi) pi.Name)
    13.  
    14.     'Check for system colours, e.g. ButtonFace, Control, HighlightText.
    15.     If systemColorNames.Any(Function(scn) String.Equals(scn, name, StringComparison.OrdinalIgnoreCase)) Then
    16.         'The input matches a system colour.
    17.         Return False
    18.     End If
    19.  
    20.     'The specified colour is known but is not part of the system.
    21.     Return True
    22. End Function
    The issue with that is that it will match "li ghtbl ue" as well as "light blue". The more rigorous option is to insert single spaces before upper-case letters within the field and property names:
    vb.net Code:
    1. Private Const SPACE As String = " "
    2.  
    3. Private Function IsColorName(name As String) As Boolean
    4.     Dim knownColorNames As IEnumerable(Of String) = [Enum].GetNames(GetType(KnownColor))
    5.  
    6.     If name.Contains(SPACE) Then
    7.         'The input contains at least one space so insert spaces into the known colour names for matching.
    8.         knownColorNames = knownColorNames.Select(Function(kcn) InsertSpacesBetweenWords(kcn))
    9.     End If
    10.  
    11.     'Check for known colours, e.g. Red, LightBlue, Control.
    12.     If Not knownColorNames.Any(Function(kcn) String.Equals(kcn, name, StringComparison.OrdinalIgnoreCase)) Then
    13.         'The input does not match a known colour.
    14.         Return False
    15.     End If
    16.  
    17.     Dim systemColorNames = GetType(SystemColors).GetProperties(BindingFlags.Public Or BindingFlags.Static).Select(Function(pi) pi.Name)
    18.  
    19.     If name.Contains(SPACE) Then
    20.         'The input contains at least one space so insert spaces into the system colour names for matching.
    21.         systemColorNames = systemColorNames.Select(Function(scn) InsertSpacesBetweenWords(scn))
    22.     End If
    23.  
    24.     'Check for system colours, e.g. ButtonFace, Control, HighlightText.
    25.     If systemColorNames.Any(Function(scn) String.Equals(scn, name, StringComparison.OrdinalIgnoreCase)) Then
    26.         'The input matches a system colour.
    27.         Return False
    28.     End If
    29.  
    30.     'The specified colour is known but is not part of the system.
    31.     Return True
    32. End Function
    33.  
    34. Private Function InsertSpacesBetweenWords(text As String) As String
    35.     For i = text.Length - 1 To 1 Step -1
    36.         If Char.IsUpper(text(i)) Then
    37.             text = text.Insert(i, SPACE)
    38.         End If
    39.     Next
    40.  
    41.     Return text
    42. End Function
    Sample usage:
    vb.net Code:
    1. Dim colourNames = {"Red", "blue", "Groan", "control", "Window", "light blue", "li    ghtbl ue", "highlight text", "hig hlightte xt"}
    2.  
    3. For Each colourName As String In colourNames
    4.     Console.WriteLine($"{colourName}: {IsColorName(colourName)}")
    5. Next
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: [RESOLVED] Problem with Color.FromName

    If you wanted to give a color preview for your color selection process, you could use an extended combobox...

    Code:
    Public Class colorComboBox
        Inherits ComboBox
    
        Public Sub New()
            Me.DropDownStyle = ComboBoxStyle.DropDownList
            Me.DrawMode = Windows.Forms.DrawMode.OwnerDrawVariable
            MyBase.Items.Clear()
            MyBase.Items.AddRange([Enum].GetNames(GetType(KnownColor)).OrderBy(Function(n) Color.FromName(n).GetHue).ToArray)
        End Sub
    
        Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
            Dim c As Color = Color.Empty
            If e.Index <> -1 Then
                c = Color.FromName(MyBase.Items(e.Index).ToString)
            End If
            If (e.State And DrawItemState.ComboBoxEdit) = DrawItemState.ComboBoxEdit Then
                ' Draw the contents of the edit area of the combo box.
                e.Graphics.FillRectangle(New SolidBrush(c), New Rectangle(4, e.Bounds.Top + 1, 16, 12))
                e.Graphics.DrawRectangle(Pens.Black, New Rectangle(4, e.Bounds.Top + 1, 16, 12))
                e.Graphics.DrawString(If(c.Name = "0", "Empty", c.Name), Me.Font, Brushes.Black, 22, e.Bounds.Top + 1)
            Else
                ' Draw the contents of an item in the drop down list.
                e.Graphics.FillRectangle(New SolidBrush(c), New Rectangle(2, e.Bounds.Top + 2, 16, 12))
                e.Graphics.DrawRectangle(Pens.Black, New Rectangle(2, e.Bounds.Top + 2, 16, 12))
                e.Graphics.DrawString(c.Name, Me.Font, Brushes.Black, 20, e.Bounds.Top + 2)
                ' Draw the focus rectangle.
                e.DrawFocusRectangle()
            End If
            MyBase.OnDrawItem(e)
        End Sub
    
        Public Function getSelectedColor() As Color
            If MyBase.SelectedIndex > -1 Then
                Return Color.FromName(MyBase.Text)
            Else
                Return Color.Transparent
            End If
        End Function
    
    End Class
    Name:  222.png
Views: 1413
Size:  2.5 KB
    Last edited by .paul.; Sep 26th, 2020 at 03:09 PM.

  15. #15

    Thread Starter
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,500

    Re: [RESOLVED] Problem with Color.FromName

    Quote Originally Posted by .paul. View Post
    Why declare colours(2) and chk(2)???
    You’re only using 2 elements in both. You know arrays are zero based, but you need to declare arrays with the Upperbound and not the Length...

    I.e. colours(1), chk(1)
    Oh !
    I've always used length, maybe from my original BASIC language from the 1970's.

    Poppa
    Along with the sunshine there has to be a little rain sometime.

  16. #16
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: [RESOLVED] Problem with Color.FromName

    Quote Originally Posted by Poppa Mintin View Post
    Oh !
    I've always used length, maybe from my original BASIC language from the 1970's.

    Poppa
    Color choice in your 70's BASIC would be easy. These days choosing knowncolors is more complicated. I'd still use my extended combobox. It avoids user error. Allowing text entry in a textbox for color choosing isn't an efficient method...

  17. #17
    Fanatic Member Delaney's Avatar
    Join Date
    Nov 2019
    Location
    Paris, France
    Posts
    846

    Re: [RESOLVED] Problem with Color.FromName

    Quote Originally Posted by .paul. View Post
    If you wanted to give a color preview for your color selection process, you could use an extended combobox...
    That's a nice tips, thanks (need to spread some rep before being able to give some to you).

    I wonder if I can replace the colored rectangle with an image...?? I will try that as a good exercise.
    The best friend of any programmer is a search engine
    "Don't wish it was easier, wish you were better. Don't wish for less problems, wish for more skills. Don't wish for less challenges, wish for more wisdom" (J. Rohn)
    “They did not know it was impossible so they did it” (Mark Twain)

  18. #18
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,130

    Re: [RESOLVED] Problem with Color.FromName

    Quote Originally Posted by .paul. View Post
    If you wanted to give a color preview for your color selection process, you could use an extended combobox...

    Code:
    Public Class colorComboBox
        Inherits ComboBox
    
        Public Sub New()
            Me.DropDownStyle = ComboBoxStyle.DropDownList
            Me.DrawMode = Windows.Forms.DrawMode.OwnerDrawVariable
            MyBase.Items.Clear()
            MyBase.Items.AddRange([Enum].GetNames(GetType(KnownColor)).OrderBy(Function(n) Color.FromName(n).GetHue).ToArray)
        End Sub
    
        Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
            Dim c As Color = Color.Empty
            If e.Index <> -1 Then
                c = Color.FromName(MyBase.Items(e.Index).ToString)
            End If
            If (e.State And DrawItemState.ComboBoxEdit) = DrawItemState.ComboBoxEdit Then
                ' Draw the contents of the edit area of the combo box.
                e.Graphics.FillRectangle(New SolidBrush(c), New Rectangle(4, e.Bounds.Top + 1, 16, 12))
                e.Graphics.DrawRectangle(Pens.Black, New Rectangle(4, e.Bounds.Top + 1, 16, 12))
                e.Graphics.DrawString(If(c.Name = "0", "Empty", c.Name), Me.Font, Brushes.Black, 22, e.Bounds.Top + 1)
            Else
                ' Draw the contents of an item in the drop down list.
                e.Graphics.FillRectangle(New SolidBrush(c), New Rectangle(2, e.Bounds.Top + 2, 16, 12))
                e.Graphics.DrawRectangle(Pens.Black, New Rectangle(2, e.Bounds.Top + 2, 16, 12))
                e.Graphics.DrawString(c.Name, Me.Font, Brushes.Black, 20, e.Bounds.Top + 2)
                ' Draw the focus rectangle.
                e.DrawFocusRectangle()
            End If
            MyBase.OnDrawItem(e)
        End Sub
    
        Public Function getSelectedColor() As Color
            If MyBase.SelectedIndex > -1 Then
                Return Color.FromName(MyBase.Text)
            Else
                Return Color.Transparent
            End If
        End Function
    
    End Class
    Name:  222.png
Views: 1413
Size:  2.5 KB
    nice one
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  19. #19
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: [RESOLVED] Problem with Color.FromName

    Quote Originally Posted by Delaney View Post
    I wonder if I can replace the colored rectangle with an image...?? I will try that as a good exercise.
    You can draw anything you choose in the DrawItem event, but it helps to have something that relates to the item, as in this case...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width