【发布时间】:2016-03-18 21:21:42
【问题描述】:
我正在使用 WinForms 在 C# 中创建一个应用程序。
我想要什么:
我想要一个侧面有箭头的按钮。当按下带有箭头的按钮部分时,它将显示一个下拉菜单,但如果按下按钮的任何其他部分,则它应该触发鼠标单击事件。
我需要什么帮助:
我相信我可以使用鼠标位置进行鼠标位置检查,但是当它是按钮的主要部分时,如何确保按钮实例的事件处理程序只有一个“鼠标按下”事件被点击? IE。如何在基本处理程序中处理事件,使其永远不会到达派生事件?
我有什么:
我的代码结构(简化)如下(取自Windows.Forms button with drop-down menu):
// Button class:
public class ButtonWithDropDown : Button
{
protected override void OnClick(EventArgs e)
{
// Check for when the mouse is on the button and dispose of the
// event if it's over the 'arrow' part of the button.
}
}
// Event handler:
private void btnClickMe_Click(object sender, EventArgs e)
{
MouseEventArgs mevent = (MouseEventArgs)e;
if (mevent.Button == System.Windows.Forms.MouseButtons.Left)
MessageBox.Show("Only shown when clicking the main part of the button");
}
谢谢。
【问题讨论】:
-
有一个空的
override,你不能在其中调用base。 -
@David Pine 喜欢示例代码吗? (我的实际代码确实调用了
base.OnClick(e))不幸的是我已经尝试删除它,它仍然通过事件。 -
您是要避免
.Click事件有任何侦听器,还是要完全阻止override void OnClick被调用? -
另外,还有一些特定于鼠标的不同事件……看看msdn.microsoft.com/en-us/library/…
-
MouseClick是一个不同的事件,如果你不喜欢它触发,你应该覆盖OnMouseClick并且不要调用base.OnMouseClick(e)