简体   繁体   中英

What is the best way to trap key press combinations in owner form?

I have a global parent form with multiple child forms and would like to have a shortcut key combination for the user to cycle between them. I would like this logic to be handled by the parent form so that the child forms are kept independent of this.

This apparently common scenario (eg switching active documents in Visual Studio, active tabs in browsers, etc) has proven surprisingly hard to implement. The only way I found of doing it so far is to use a global hook or a hotkey. The problem with this approach is that they stop other applications from using the same hotkey, as the setting is applied system-wide.

What is the best way for an owner form to listen for particular key presses even when the child forms are in focus?

Ok, I found an easy way to do it using message filters. It turns out you can register global message filters with an Application using the IMessageFilter interface. For example:

class HotKeyMessageFilter : IMessageFilter
{
    const int WM_KEYDOWN = 0x100;

    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN)
        {
            var keyCode = (Keys)m.WParam;
            if (keyCode == Keys.Tab && Form.ModifierKeys.HasFlag(Keys.Control))
            {
                if (Form.ModifierKeys.HasFlag(Keys.Shift)) CycleActiveForm(-1);
                else CycleActiveForm(1);
            }
        }

        return false;
    }
}

This message filter will listen for a particular key combination and then call some static or class method in order to jump between all open windows. You can pass specific window handles that you want to cycle between as arguments to the message filter, as it is just a normal class.

You can register filters with the application at any moment with the following:

Application.AddMessageFilter(filter);

and remove it with the following:

Application.RemoveMessageFilter(filter);

If using an MDI form in winforms, the Ctrl + Tab shortcut will automatically be registered for changing windows. If you're trying to trap for other key combinations, set KeyPreview to true on your MDI form and handle the key presses there..

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