如何捕获真实(真实)鼠标点击

时间:2014-04-22 15:33:06

标签: c# winforms

我有一些代码(C#WINFORM)

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
  // How to find out?
}

我还在Form_Load上调用该事件:

myGrid_CellClick(dgvDropsToVal, new DataGridViewCellEventArgs(0, 0));

如何找出真正的鼠标点击或从myGrid_CellClick中的Form_Load触发?
其他然后在Form_Load上的bool标志。

4 个答案:

答案 0 :(得分:2)

添加辅助方法:

private void myForm_Load(object sender, EventArgs e)
{
    DoSomething(false);
}

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DoSomething(true);
}

private void DoSomething(bool wasClicked)
{
}

答案 1 :(得分:0)

为什么要手动调用事件处理程序方法?它会让其他程序员感到困惑。创建单独的方法并使意图清晰。将代码保存在我的身上并不是代码的唯一消费者。

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
  CellClickAction(parameter);
}

private void CellClickAction(Whatever parameter)
{
   //Do whatever
}

在表单加载中,您可以调用相同的方法。

private void form_Load(object sender, EventArgs e)
{
     CellClickAction(parameter);//parameter will say the source of method call
}

现在,您可以修改Whatever参数以区分方法调用的来源。这使代码清晰。

答案 2 :(得分:0)

我会使用带有标志的辅助方法,因为这不会增加开销。如果您坚持编程错误,那么您可以查看StackFrame或使用CallerMemberNameAttribute

请参阅:How do I get the calling method name and type using reflection?

private void myForm_Load(object sender, EventArgs e)
{
    DoSomething();
}

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DoSomething();
}

private void DoSomething([CallerMemberName] string caller = "")
{
    // caller will contain "myForm_Load" or "myGrid_CellClick"
}

你将受到反射开销的惩罚。

答案 3 :(得分:0)

使用发送者参数怎么样?

private void myForm_Load(object sender, EventArgs e)
{
    myGrid_CellClick(null, null);
}

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (sender == null)
    {
        //called yourself in Form_Load
    }
    else
    {
        //called by control
    }
}
相关问题