简体   繁体   中英

c# call KeyDown event from a DoubleClick event

I have some code written in my KeyDown event that I want to execute from a Double Click event. I could wrap that code block as a function and call that function in both events, but I just want to use a fancy way to avoid creating a new function. This is what my two events look like.

private void txtProduct_KeyDown(object sender, KeyEventArgs e)  
{  
    if(e.KeyCode == Keys.Return)  
    {
        //do something  
    }  
}  

private void listProduct_DoubleClick(object sender, EventArgs e)
{
    txtProduct_KeyDown(txtProduct, Keys.Return);
}  

In order to execute the //do something block from doubleclick event, I need to call keydown event with two specific arguments. what is it? any help?

Don't go there. Always extract common functionality into its own method. Trying fancy stuff to avoid creating a new method will only cause you pain in the long run.

private void txtProduct_KeyDown(object sender, KeyEventArgs e)  
{  
    if(e.KeyCode == Keys.Return)  
    {
        DoSomething(); 
    }  
}  

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

private void DoSomething()
{
    // Do Something
}

That is painless and expresses exactly what you want to do, namely DoSomething both on list doubleclick and Return Keydown.

To pass KeyEventArgs you need this

txtProduct_KeyDown(txtProduct, new KeyEventArgs(Keys.Enter));

Although it's not the best way to do it as coding practices are concerned, you should create a function which performs that dosomething for you and then call it from anywhere in the world.

以下代码将 Enter Key Press 事件传递给特定方法。

txtProduct_KeyDown(new object(), new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Enter));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM