开发者

How to set the hand cursor on a mouse move for all buttons in C#?

I've been setting each button's events manually, but how can I generalize this?

I suppose I could override ButtonBase, but how do I do that? I'm a relatively new C# programmer and开发者_如何学JAVA I need this because I'm simulating a real device, so I need the cursor to change so the user will know where they can click.


If all the buttons are on the form (no nesting containers) then you can do something like this on Form_Load()

foreach(Button b in this.Controls.OfType<Button>())
{
    b.MouseEnter += (s, e) => b.Cursor = Cursors.Hand;
    b.MouseLeave += (s, e) => b.Cursor = Cursors.Arrow;
}

If you don't want to touch every button on the form, you can do a simple collection and iterate over them

Button[] buttons = new[] {button1, button2, button3};

foreach (Button b in buttons)
{
    b.MouseEnter += (s, e) => b.Cursor = Cursors.Hand;
    b.MouseLeave += (s, e) => b.Cursor = Cursors.Arrow;
}


Create a new "Class Library" project and make a new class like this:

public class ExtendedButton:Button
{
    public ExtendedButton()
    {
        MouseEnter += (s, e) => Cursor = Cursors.Hand;
        MouseLeave += (s, e) => Cursor = Cursors.Arrow;
    }
}

On a Windows Form project, add a reference to your new library and on the form, add an ExtendedButton control instead of Button.


You can do it in Visual Studio Designer. Select all buttons by Ctrl-click'ing and change the Cursor property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜