Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an image button in .NET Winforms application

I'm trying to create a button in my .NET 4.0 Winforms app in Visual Studio 2010 that is ONLY an image. I have a window that is borderless and has a background image that makes up my custom skin for this application. For the close/minimize buttons in the top right of the window, I wanted to create 2 simple buttons that are images only that look like the typical Windows close/minimize buttons.

I may be going about this design wrong, so if I am please let me know. So far I've determined that I need to create a subclass for Button that only renders the image. The final implementation needs to render different images for each button state (normal, hover, clicked, etc). Here is what I have so far:

public class ImageButton : Button
{
    Pen pen = new Pen( Color.Red, 1.0f );

    public ImageButton()
    {
        SetClientSizeCore( BackgroundImage.Width, BackgroundImage.Height );
    }

    protected override void OnPaint( PaintEventArgs e )
    {
        e.Graphics.DrawImage( BackgroundImage, 0, 0 );
        //e.Graphics.DrawRectangle( pen, ClientRectangle );
        //Rectangle bounds = new Rectangle( 0, 0, Width, Height );
        //ButtonRenderer.DrawButton( e.Graphics, bounds, PushButtonState.Normal );
        //base.OnPaint(pevent);
    }

    protected override void OnPaintBackground( PaintEventArgs e )
    {
        // Do nothing
    }
}

At this point, assuming this design is appropriate, I need to know how to call SetClientSizeCore() appropriately. Calling it in the constructor raises an exception. I assume this is because the control hasn't had a chance to initialize yet. I'm not sure what function to override that will allow me to change the size of my button to fit the image after it has been initialized by .NET. Any ideas on this?

like image 939
void.pointer Avatar asked Jan 25 '11 16:01

void.pointer


2 Answers

In the constructor, BackgroundImage is null.

You need to set the size when BackgroundImage is changed by overriding the property.

You should also shadow the Size property and add [DesignerSerializationVisibilty(DesignerSerializationVisibility.Hidden)] to prevent the size from being saved by the designer.

like image 97
SLaks Avatar answered Oct 20 '22 18:10

SLaks


Wait until the BackgroundImage property is assigned so you'll know what size you need. Override the property like this:

public override Image BackgroundImage {
    get { return base.BackgroundImage; }
    set {
        base.BackgroundImage = value;
        if (value != null) this.Size = value.Size;
    }
}
like image 39
Hans Passant Avatar answered Oct 20 '22 18:10

Hans Passant