Search code examples
c#timerkeypress

How Multiple keypress in Timer or timer altnernative?


private void timer1_Tick(object sender, EventArgs e){

if (Form.ModifierKeys == System.Windows.Forms.Keys.Control
 && Form.ModifierKeys == System.Windows.Forms.Keys.Enter)

my_translate(textbox1.text); 

}

.

I try it but dont work how can I do it?

I am writing a dictionary software; with timer I check determine pressed keys so I translate word. I cant use textBox1_KeyPress etc. because I get text from .doc/.txt so I need timer for get text.

//The code is working
private void timer1_Tick(object sender, EventArgs e){ 
    MouseButtons aa = MouseButtons;
    if (aa == MouseButtons.Middle && Form.ModifierKeys == Keys.Control)

            my_translate();
} 

.

And We have a alnernative for timer to call a method when user pressed a key combination?


Solution

  • Your current code

    if (Form.ModifierKeys == System.Windows.Forms.Keys.Control && 
        Form.ModifierKeys == System.Windows.Forms.Keys.Enter)
    

    means "if the keys pressed equals the control key AND the keys pressed equals the enter key". This will never happen, because if only the control key is pressed, the enter key is not pressed, and vise versa.

    I believe you wanted this:

    if (Form.ModifierKeys.HasFlag(Keys.Control) && 
        Form.ModifierKeys.HasFlag(Keys.Enter))
    

    This means "if the keys pressed includes the control key and the enter key".

    You shouldn't use timers for this anyways. Look into the Control.KeyPress event and use that instead. You can use the timer to load the text file while using events to handle the key press.

    I suggest you read more about the KeyPress event on MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx