在C#迷你应用程序中,我有一个按钮,我想通过右键单击来启用和禁用它。也就是说,当通过右键单击启用按钮时,它将变为禁用;当禁用按钮时,右键单击将其状态更改为启用。禁用已启用的按钮非常简单明了,但是无法通过右键单击启用它;因为该按钮已禁用,并且没有将事件发送到无效代码。 我该怎么办?
答案 0 :(得分:3)
已禁用控件的鼠标事件将向下传递到其Parent
。
您可以在那里找到它们并测试光标是否在按钮上。
示例:
if (button1.Bounds.Contains(e.Location)) button1.Enabled = true;
如果有几个按钮,则需要全部测试。.
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
foreach (Control ctl in panel1.Controls)
{
if (ctl is Button && ctl.Bounds.Contains(e.Location))
ctl.Enabled = true;
}
}
如果仅应启用鼠标右键,则可以为此添加一个测试:
if (e.Button.HasFlag(MouseButtons.Right) &&
ctl is Button && ctl.Bounds.Contains(e.Location))
答案 1 :(得分:0)
右键单击以启用和禁用按钮不是标准或推荐的按钮行为,因此API完全没有为它提供简单的实现。禁用按钮后,它将不再捕获鼠标事件,但表单会捕获鼠标事件。
public partial class Form1 : Form
{
private Boolean _button1IsRightClicked;
public Form1()
{
InitializeComponent();
_button1IsRightClicked = false;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hi");
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.X >= button1.Location.X && e.X <= (button1.Location.X + button1.Width) &&
e.Y >= button1.Location.Y && e.Y <= (button1.Location.Y + button1.Height))
{
_button1IsRightClicked = true;
}
else
{
_button1IsRightClicked = false;
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (e.X >= button1.Location.X && e.X <= (button1.Location.X + button1.Width) &&
e.Y >= button1.Location.Y && e.Y <= (button1.Location.Y + button1.Height))
{
_button1IsRightClicked = false;
enableDisableButton1(button1.Enabled);
}
else
{
_button1IsRightClicked = false;
}
}
private void enableDisableButton1(Boolean isEnabled)
{
if (isEnabled)
{
button1.Enabled = false;
isEnabled = false;
}else
{
button1.Enabled = true;
isEnabled = true;
}
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
_button1IsRightClicked = true;
}
else
{
_button1IsRightClicked = false;
}
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right && _button1IsRightClicked == true)
{
_button1IsRightClicked = false;
enableDisableButton1(button1.Enabled);
}
else
{
_button1IsRightClicked = false;
}
}
}