Using the Choose Color Dialog Box
Now that you understand what is to passed to the API function in-order for it to work, we now need to put this into practice, by building a sample project that will:
- Display the ChooseColour Common Dialog box
- Allow selection of all colours including custom colours
- When OK is clicked retrieve the chosen colour and set the form's back colour to the colour chosen.
First start a new standard-exe project, add a standard module to the project and a command button to form1. Set the command button's name and caption properties to ChooseColour.
Before we start, we need to ensure that all the correct declarations are in the standard module.
Public Type CHOOSECOLOR lStructSize As Long hwndOwner As Long hInstance As Long rgbResult As Long lpCustColors As String flags As Long lCustData As Long lpfnHook As Long lpTemplateName As String End Type Public Declare Function ShowColour Lib _ "comdlg32.dll" Alias "ChooseColorA" _ (pChoosecolor As CHOOSECOLOR) As Long
Make sure these are correctly copied or the call will fail.
Go back to the click procedure of the ChooseColour command button on form1 as we now need to add the code make this work.
Below is the code that will make the function work correctly make sure that you understand how all of the code works by reading the detailed comments. This sample, will only demonstrate the basic opening of the common dialog box.
Private Sub ChooseColour_Click() Dim CustomColours() As Byte ' Define array for custom colours. ReDim CustomColours(0 To 15) As Byte ' Resize the array to hold the elements Dim tChooseColour As CHOOSECOLOR ' Declare a user-defined variable for the ChooseColour ' type structure. With tChooseColour .hwndOwner = Me.hWnd ' Set the handle for the owner of the window. .lpCustColors = StrConv(CustomColours, vbUnicode) ' Pass the custom colours array after converting ' it to Unicode using the StrConv function. .flags = 0& ' For this sample, we do not need to use this. .lStructSize = Len(tChooseColour) ' Set the size of the type structure End With If ShowColour(tChooseColour) = 0 Then MsgBox _ "You clicked on the 'Cancel' button", _ vbExclamation: Exit Sub ' Call the API function and display the ChooseColour ' Common Dialog box, and if the users clicks on cancel ' then the function will return 0. Me.BackColor = tChooseColour.rgbResult ' Set the back colour of the form to the colour ' that the user selected. End Sub
If you now run the application and click on the ChooseColour command button then the Common Dialog will be displayed.
Download choosecolor demonstration project.
You should now be able to implement the Color Dialog box into your application without using the chunky 140Kb common dialog box control. Next week I will show you how to use the standard Page Setup dialog box that is not available with any OCX! Stay tuned!
If you have any queries about this article, please email me.
Page 3 of 3