[英]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? 我想我可以覆盖ButtonBase,但是我该怎么做呢? I'm a relatively new C# programmer and 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.
我是一个相对较新的C#程序员,我需要这个,因为我正在模拟一个真实的设备,因此我需要更改光标,以便用户知道他们可以单击的地方。
If all the buttons are on the form (no nesting containers) then you can do something like this on Form_Load()
如果所有按钮都在表单上(没有嵌套容器),则可以在
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. 在Windows窗体项目上,添加对新库的引用,在窗体上,添加ExtendedButton控件而不是Button。
You can do it in Visual Studio Designer. 您可以在Visual Studio Designer中完成。 Select all buttons by Ctrl -click'ing and change the Cursor property .
按住Ctrl单击并选择所有按钮,然后更改Cursor属性 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.