c# keypress listening in background
private void button1_Click(object sender, EventArgs e)
{
Keys 开发者_如何学Pythonkey = new Keys();
while (true)
{
if (key == Keys.F5)
{
MessageBox.Show("F5");
}
else if (key == Keys.F4)
{
MessageBox.Show("F4");
}
}
}
How can I make this run in the background when the form is out of focus? My ultimate goal is to make this run in the background, and wait for the F5/F4 key to be pressed.
I'm not entirely sure what your question is. If you want to register a global hotkey you can use the windows api function RegisterHotKey.
There are already a few questions on SO answering how to use this function in C#.
If you want a hot-key that's only active on a certain control or form you can use the events supplied by WinForms.
If you want to be notifed of all key-presses on the desktop then a low level keyboard hook is appropriate. But don't use a hook if you just want a global hotkey.
Your code itself doesn't make much sense. new Keys()
just returns the default value of the Keys
enum(Keys.None
I guess) which is never equal to F4 or F5.
Not sure what the relationship is between the button1 and keypress, but take a look at the KeyPressEventHandler
Code example below, displays the last key pressed:
private void button1_Click(object sender, EventArgs e)
{
this.textBox1.KeyPress += new KeyPressEventHandler(keypressed);
}
private void keypressed(Object o, KeyPressEventArgs e)
{
label1.Text = e.KeyChar.ToString();
}
精彩评论