Click here to Skip to main content
Email Password   helpLost your password?

Sample Image - ColourButtons.gif

Introduction

I have written this article for two reasons. The first is that, while the standard .NET framework allows you to change the color of buttons, this feature is missing from the compact framework. The buttons in the compact framework are a boring black on grey. The second reason for writing this article is that, whilst it is relatively straightforward to write standard controls, writing controls for the compact framework is slightly more challenging, since there isn't a project template for the compact framework controls in Visual Studio. I would imagine that both of these issues will be resolved in time by Microsoft, but for the time being, a user control is required and this control is not trivial to write.

Creating the Control

There are already several articles describing how to create a control for the compact framework, so I won't duplicate those articles here. In my opinion, one of the better articles is on the MSDN site: Creating Custom Controls for the .NET Compact Framework by Chris Kinsman, Vergent Software, September 2002. It took me a while to get this to work, but that turned out to be because there are quite a few steps to follow and you have to make sure you don't miss any out!

The Code

Having created a blank control, I set about changing it to work as a button. I wanted to create a button that behaved the same way as the standard .NET CF button, but had more colors. I decided to give the button, 4 new color properties. These are:

Color m_NormalBtnColour = Color.LightYellow;
Color m_NormalTxtColour = Color.Blue;
Color m_PushedBtnColour = Color.Blue;
Color m_PushedTxtColour = Color.Yellow;

The properties of these are exposed by the control using the following code (which shows one of the four - the others are identical with different names and descriptions):

#if NETCFDESIGNTIME
    [Category("Appearance")]
    [DefaultValue(3)]
    [Description("The normal colour of the button.")]
#endif
public Color NormalBtnColour
{
    set
    {
        m_NormalBtnColour = value;
        Invalidate();
    }
    get
    {
        return m_NormalBtnColour;
    }
}

Note that I invalidate the control after the color has been changed. This is so that the control is redrawn when the color is changed whilst designing the form. I also had to remove the two standard color properties: BackColor and ForeColor. I did this with the following code (one of two shown):

#if NETCFDESIGNTIME
    false)>
    [EditorBrowsable(EditorBrowsableState.Never)]
#endif
public override Color BackColor
{
    set
    {;}
    get
    { return new Color(); }
}

Browsable(false) removes the item from the property window, and EditorBrowsable(Never) prevents intellisense from displaying the property. Finally, for the attributes, I added the button state, which is either normal or pushed.

public enum States 
{ 
    Normal, 
    Pushed 
}

States m_state;

This was set to normal in the constructor, and would be set to pushed on a mouse down event and back to normal on a mouse up event. Also, in order that the button was correctly drawn in design mode, OnResize was overridden to invalidate the control when the button was resized.

protected override void OnMouseDown(
            System.Windows.Forms.MouseEventArgs e) 
{
    m_state = States.Pushed; 
    // button receives input focus

    Focus();  
    base.OnMouseDown(e); 
    Invalidate(); 
} 

protected override void OnMouseUp(
            System.Windows.Forms.MouseEventArgs e) 
{
    m_state = States.Normal;
    base.OnMouseUp(e);
    Invalidate();
}

protected override void OnResize(EventArgs e)
{
    base.OnResize(e);
    Invalidate();
}

The only thing left to do was the OnPaint method. This draws the button using the two normal colors if the button is in the normal state, or the two pushed colors if the button is in the pushed state.

protected override void OnPaint(PaintEventArgs e) 
{
    Graphics graphics = e.Graphics;

    Pen pen;
    SolidBrush brush;
    SolidBrush textBrush;

    //Work out the colours that we should be using

    // for the text and background

    if (m_state == States.Normal)
    {
        brush = new SolidBrush(m_NormalBtnColour);
        textBrush = new SolidBrush(m_NormalTxtColour);
        pen = new Pen(m_NormalTxtColour);
    }
    else
    {
        brush = new SolidBrush(m_PushedBtnColour);
        textBrush = new SolidBrush(m_PushedTxtColour);
        pen = new Pen(m_PushedTxtColour);
    }

    //Draw a rectangle and fill the inside

    graphics.FillRectangle(brush, 0, 0, Width, Height);
    graphics.DrawRectangle(pen, 0, 0, Width-1, Height-1);

    //Create a font based on the default font

    int fontHeight = 10;
    Font font = new Font(FontFamily.GenericSerif,
               fontHeight, FontStyle.Bold);

    //Find out the size of the text

    SizeF textSize = new SizeF();
    textSize = e.Graphics.MeasureString(Text, font);

    //Work out how to position the text centrally

    float x=0,y=0;
    if (textSize.Width < Width)
        x = (Width - textSize.Width) /2;
    if (textSize.Height < Height)
        y = (Height - textSize.Height) /2;

    //Draw the text in the centre of the button using

    // the default font

    graphics.DrawString(Text, font, textBrush, x, y);
}

As described in the "building controls" articles, there are 2 solutions, one for the actual control, and one for the control in the designer. I wrote a batch file to build both solutions and copy the assemblies to the correct location, so that they could be picked up by Visual Studio. Once the controls have been added to "My User Controls", they can be dragged onto forms and manipulated just like any other control.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
QuestionWhere do you set the default size of the button?
lagu2653
21:32 27 Sep '06  
For some reason, which I cannot figure out, when you add a new button to a form the default size is always 200 x 200 pixels. I've opened up all files in the entire package in Emacs and searched for the string "200". I got no relevant hits. Is that size inherited from System.Windows.Forms.Control? How do I set a new default size? I tried to do it in the constructor with no luck.

/Lars

GeneralCORAL 64 / CORAL66
blashyrk123
0:06 30 Mar '06  
Hello Jon,

my name is Aaron Jones and I am hailing from Edith Cowan University in Perth, Western Australia.
I am emailing in regards to CORAL64/CORAL66. I know this is probably off-topic for the association of the board, but I am desperately seeking information (anything and everything) about the CORAL language. There seems to be references online, but very little meaningful informationConfused , apart from xgc.com . Is CORAL still classified? I saw a letter from the British Defence secretary officialy stating CORAL was no longer being used in the Royal Navy.

As a summary of the types of information, I guess what I am looking for is:

syntax and semantics, lexical analysis and parsing, names, bindings, scope, data types and records, expressions and assignments, conditional and unconditional program flow. I seem to uncomfortably understand that it is possible to both interpret and compile the language.
As for definitions of actual COMPILER for coral64 / coral66, I would be interested too. It makes sense that CORAL is classified being onboard a military vessel, as well as there is little reference to it Smile

It would be great if you could at least point me in the right direction for resources on CORAL. CORAL code may help to a certain degree, such that I can ascertain the above mentioned classifications. if you are interested in where I got your email address, I can give you the source.

I thankyou for your council,
Aaron Jones
GeneralFonts not changing
Jay Dubal
4:59 31 May '05  
Hello,

This is a nice article! Smile

btnTest.Font = new System.Drawing.Font("Arial", 4F, System.Drawing.FontStyle.Regular);

What is wrong in this? The button never seem to take new fonts!Frown

Thanks
Jay Dubal
GeneralRe: Fonts not changing
Jay Dubal
5:02 31 May '05  
//Create a font based on the default font
int fontHeight = 10;
Font font = new Font(FontFamily.GenericSerif, fontHeight, FontStyle.Bold);


!?! Smile (Little late Smile )
GeneralMisc. Comments
Whizzard9992
11:19 21 Oct '04  
The link to the Article on creating custom controls is a redirect. I had to do a google search to get the actual article. Seems like an MSDN thing.

Just a little critique, if I may Wink The SET accessors on your properties are blank. Is there a reason you did that? They should either not exist, or throw a NotSupportedException if they're virtual.

It would be nice if you went into a little more detail on how to get VS to recognize user controls. I've had to do some digging to get my answer, and a paragraph or 2 on just the mechanics of getting VS to recognize custom controls design-time would be a platinum addition to an otherwise good article.


Thanks.
GeneralTrubles with adding control to the form
Andrew Khimenko
2:05 14 Jul '04  
I have built control dlls and added ColourButton control to UserControls page.
Now I can drag ColourButton to the form only in WindowsApplication. When trying drag it on form in PocketPC Application I cannot.

What problem could be there?
GeneralRe: Trubles with adding control to the form
Jon Nethercott
10:08 14 Jul '04  
Andrew,

The most obvious thing I can think of is - have you added the ColourControl.dll? You have to add the ColourControl.Design.dll in order for Visual Studio to recognise the control properly. If it's not that, my second thought is that maybe your references are set to the windows dlls instead of the compact framework dlls.

Hope that helps,
Jon.

GeneralIncrease draw speed
RojM
18:13 8 Jun '04  
Jon - Great article and easy to understand. I'm writing an application which will use many buttons (colored) and using the Color Button I'm finding the draw speed to be rather slow i.e. I can see the individual buttons being drawn. Can you think of anything I could do to speed the process up.

Roj
GeneralRe: Increase draw speed
Jon Nethercott
13:56 9 Jun '04  
Roj

Well I tried this on my HP IPaq 2200. I have written a calculator which has 37 buttons. It seems to take about 0.3 – 0.5 sec to redraw the entire screen – i.e. about 10ms per button – which now you mention it, does seem a bit slow! I had another look at the code, and can’t see anything obvious that would be causing it to take that long – all the drawing methods (FillRectangle, DrawString) should be pretty quick.

Sorry I haven’t got any good answers! …but I will look into it later when I get a chance.

Jon.

General3D style buttons
Glamiac
8:32 23 Jan '04  
Is there any way to derive from System.Windows.Form.Button, keep the 3D look, but change the text color/background color/shape/etc.

Thanks,

Joshua Moore
Software Developer
GeneralRe: 3D style buttons
Jon Nethercott
12:52 25 Jan '04  
Joshua,

I think it should be possible to derive from Form.Button, but I couldn't get that to work. Also, as far as the compact framework buttons are concerned, I'm not sure if it's worth it anyway, because there isn't a lot of functionality in there! Poke tongue If you want a 3D look on the CF you need to write that yourself, because the CF buttons are flat style buttons, which change from black on white to white on black when you click on them.

Jon.
GeneralRe: 3D style buttons
CJCraft.com
14:30 18 Feb '04  
You can derive from Form.Button, but you cannot override its OnPaint event. If you place a breakpoint the code will never be hit. You cannot override any OnPaint events, except for Form's and Panel's if I remember right.

Thanks,
Chris Craft
http://www.cjcraft.com/
GeneralColor Button is disabled in the toolbox
Gourou
9:29 14 Jan '04  
I think this is because the control is using Windows Forms Control as base class and therefore can not be dragged to mobile ASP.NET page.
GeneralRe: Color Button is disabled in the toolbox
Jon_UK39
6:54 18 Jan '04  
You have to make sure you add the design dll, not the runtime dll to the toolbox. The two DLLs are slightly different - one has the design properties in it; the other doesn't. Also, the design dll is written for the .NET framework (ie. the development PC), whereas the runtime dll is written for the compact framework (ie. the pocket pc).

Hope that helps! Smile

Jon.
Generalnice article
Jermo
8:52 8 Jan '04  
it has the advantage of being simple and clear

just for information, since the service pack 2 for the compact framework, the standard backcolor property works for buttons

GeneralNon trivial control?
Carlos H. Perez
6:10 6 Jan '04  
Maybe, I am missing something but the code you show in your article seems pretty straightforward and rather trivial to me --resources should be released and a Font object should not be created every time a paint occurs-- but still simple enough. What's the non trivial, challeging part that you mention?


Regards,
Carlos.
GeneralRe: Non trivial control?
Jon_UK39
8:18 6 Jan '04  
The code is intentionally straightforward. When I first decided that I "needed" a new button control for the compact framework, I discovered that there wasn't a project template for CF controls. The MSDN article that I have referenced does describe how to create a CF control, but goes into a lot of detail about their actual control, and doesn't clearly show how to add (and remove properties). I think that following the eleven steps mentioned in that article to create the control is quite a complicated process that you probably wouldn't want to do every time you created a new control. So as far as my control is concerned, hopefully it can serve two distinct purposes:
1. A template that can be used to build more complicated controls.
2. A useful control in it's own right that adds a bit of colour to buttons.

You're right about the resources – I'll update the code to free them at the end of the OnPaint() method (although I notice that even in the MSDN examples they don't do this a lot of the time! Big Grin ).

Regards,
Jon.

GeneralEmulator Skin
Furty
14:59 5 Jan '04  
Where did you get the skin for the emu?
GeneralRe: Emulator Skin
Jon_UK39
22:13 5 Jan '04  
It's the default VS 2003 skin.

Regards,
Jon
GeneralRe: Emulator Skin
Furty
22:39 5 Jan '04  
That's strange - the screenshot here looks nothing like the Pocket PC 2002 emulator that came with my VS.Net 2003..
GeneralRe: Emulator Skin
Jon_UK39
0:03 6 Jan '04  
Oh ok, that'll be it then - I used the Pocket PC 2003 emulator. Smile
But you're right, the PPC2002 is the default.

Cheers,
Jon.


Last Updated 5 Jan 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010