Custom Buttons in C# WinForms

2019-01-27 05:23发布

I have done a bit of research but cannot seem to find what I am looking for.

What I want to do is make a "custom" button in a windows form. This would basically just be a matter of changing the default "grey" background to a custom image. A custom image would also be used for when hovering over and clicking the button.

This is not just a matter of changing the background image as the image I want to use has rounded edges with a transparent background and I want custom image for hovering / clicked. I want everything else about the button to behave in the same manner as a normal button.

Is this possible?

2条回答
虎瘦雄心在
2楼-- · 2019-01-27 06:00

The solution I found was to set the FlatStyle of the button to Flat and set all the borders to 0. I then had a problem with the focus of the button (it displayed a little border). To solve this I followed this tutorial:

http://dotnetstep.blogspot.com/2009/06/remove-focus-rectangle-from-button.html

With this in place all I had to do was add events to the button so that the image was changed when a certain action was carried out on it:

    private void button1_MouseLeave(object sender, EventArgs e)
    {
        this.button1.Image = Properties.Resources._default;
    }

    private void button1_MouseEnter(object sender, EventArgs e)
    {
        this.button1.Image = Properties.Resources._hover;
    }        

    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        this.button1.Image = Properties.Resources._clicked;
    }

    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        this.button1.Image = Properties.Resources._default;
    }

Hope this will help someone else!

查看更多
登录 后发表回答