Creating an image button in .NET Winforms application

♀尐吖头ヾ 提交于 2020-01-14 07:59:09

问题


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?


回答1:


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.




回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/4796021/creating-an-image-button-in-net-winforms-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!