Is it Possible to Set Hotkeys in C# for a Program to Run in the Background?

  • Context: C# 
  • Thread starter Thread starter AliGh
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
AliGh
Messages
64
Reaction score
1
I have written a program in C# which presses some keys and do some mouse movements and clicks
Now i want to bind a key to my start and stop buttons (works even if window is not the active window)
I searched in google but got confused . Isn't there any easy way to do this (for example i want Alt + F2 to stop the program)
And also i saw something like this and it didnt work (unless button1.PerformClick(); is the wrong command for hitting a button)
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.F8)
{

}
}
 
on Phys.org
AliGh said:
I have written a program in C# which presses some keys and do some mouse movements and clicks
Now i want to bind a key to my start and stop buttons (works even if window is not the active window)
I searched in google but got confused . Isn't there any easy way to do this (for example i want Alt + F2 to stop the program)
And also i saw something like this and it didnt work (unless button1.PerformClick(); is the wrong command for hitting a button)
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.F8)
{

}
}
Unless the window is active, I don't believe that it will respond to keypress events. The description for PreviewKeyDown (https://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx) says (emphasis added), "Occurs before the KeyDown event when a key is pressed while focus is on this control."

I'm pretty sure that whatever window is the one that is active is the one listening for key events.
 
Mark44 said:
Unless the window is active, I don't believe that it will respond to keypress events. The description for PreviewKeyDown (https://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx) says (emphasis added), "Occurs before the KeyDown event when a key is pressed while focus is on this control."

I'm pretty sure that whatever window is the one that is active is the one listening for key events.
Any other easy way i can do this ?
Because it will be annoying to stop the program with a mouse movement process (especially for simple users they might force restart their computer to stop it :D )