控件边界内的光标

时间:2012-07-05 04:30:20

标签: c# winforms cursor contains windows-controls

public void TapeMeasure(object sender, EventArgs e)
  {
     if (TrussManager.Truss != null)
     {
        Point containerPoint = trussEditor.PointToClient(Cursor.Position);

        if (!trussEditor.MainMenu.CommandToolStrip.ClientRectangle.Contains(containerPoint))
           execute command A
        else
        execute command B
     }
  }

调用此事件
ToolStripButton commandButton = new ToolStripButton("Tape", ConvertIconToImage(icon), TapeMeasure);

ToolStripMenuItem tsmi = new ToolStripMenuItem("Tape", ConvertIconToImage(icon), TapeMeasure);

(Winforms申请)

我想知道我的光标不是我的工具条。但是,无论光标在哪里,上面的代码都会返回相同的结果。

此代码位于一个事件处理程序中,该事件处理程序从Toolstrip上的按钮或上下文菜单上的Button调用。如果在上下文菜单上调用它,我假设用户想要使用当前的鼠标点。否则我希望用户点击他们想要的点

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

由于您正在使用MouseClick事件来启动Method,因此Click事件的发件人对象将具有发起Event的对象。在这种情况下,我只确定发件人的类型,因为一个是ToolStripButton而另一个是MenuItem。正如我在聊天中提到的那样,Cursor.Point会不断更新,这是我认为会导致您出现问题的原因。

此示例将确定哪个Object生成了ClickEvent并运行了approriate方法。

public void TapeMeasure(object sender, EventArgs e) 
{ 
    if (TrussManager.Truss != null) 
    { 
        System.Type sysType = sender.GetType();

        if (!(sysType.Name == "ToolStripButton"))
            //execute command A 
        else 
            //execute command B 
    } 
} 

此示例将考虑ContextMenu的位置,并处理与单击Button时相同的方法(如果它包含在toolBar中。

public void TapeMeasure(object sender, EventArgs e) 
{ 
    if (TrussManager.Truss != null) 
    {
        System.Type sysType = sender.GetType();
        if (!(sysType.Name == "ToolStripButton"))
        {
            if (sysType.Name == "ToolStripMenuItem")
            {
                ToolStripMenuItem temp = (ToolStripMenuItem)sender;
                if (trussEditor.MainMenu.CommandToolStrip.ClientRectangle.Contains(trussEditor.MainMenu.CommandToolStrip.PointToClient(temp.Owner.Location)))
                {
                    //execute command A
                }
                else
                {
                    //execute command B
                }
            }
        }
        else
        {
            //execute command A
        }
    } 
}