Pergunta

I'm using the Window's API RegisterHotKey function to run a macro when the F2 key is pressed while a specific application is open and focused.

The problem is, this is stopping the F2 key from working for other applications, such as Excel.

How can I prevent RegisterHotKey from stopping the default action?

I have a system tray application that uses the HotKeyManager class from this answer to register hotkeys. When a specific key is pressed (for example, F2), I use the Windows API to check if a closed-source application is open and focused, and if so send it a series of SendKeys.

Foi útil?

Solução

From what I understand, you want your global hotkey to work only when one or more selected apps are focused. Can't you simply SendKeys the intercepted strokes if you determine that an incompatible app is in the foreground?

For example,

if (IsSpecificWindowFocused())
{
    // Do work
}
else
{
    // Resend the key to whatever window is current
    SendKeys.Send("{F2}");
}

Outras dicas

RegisterHotKey is global, so it is going to trap all of those keystrokes (in other words, I don't believe it is possible to do exactly what you ask).

However, this thread Global Keyboard Hooks (C#) talks about creating a keyboard message filter, which is (I believe) more like what you are going for.

To clarify: RegisterHotKey is going to be best for things like tray apps and anywhere else where you want an OS wide keyboard short cut that doesn't rely on the app being in focus.

Application.AddMessageFilter() is what you want when you want consistent handling of a particular keystroke, but only when your app already has focus.

A way to do what you're describing and still stay in .NET would be to monitor what processes are running on the OS and only enable the global hook when your app is running.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top