Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Keyboard Events from one Form to another Form

my question is quite simple:

Our C# application has one MainForm with a menu and several keyboard shortcuts associated with the menu entries.

Now we need to trigger the menu entries from some child forms too. But since the MainForm is inactive when one of the child forms is active, the shortcuts do not work.

Is there a simple way to propagate all keyboard events from the child form to the 'Owner' form? Or just to another form in general?

Ah, and we cannot use some low level windows stuff, because we need to run the application on Mono/Linux too.

EDIT: The exact problem i have is to trigger the menu items with the same shortcut from another form. Of course without updating code in the forms if the menu changes of new items are added.

like image 286
thalm Avatar asked Jun 01 '10 14:06

thalm


1 Answers

This is what fixed it for me:

public class MainForm : Form
{
    public bool ProcessCmdKeyFromChildForm(ref Message msg, Keys keyData)
    {
        Message messageCopy = msg;
        messageCopy.HWnd = this.Handle; // We need to assign our own Handle, otherwise the message is rejected!

        return ProcessCmdKey(ref messageCopy, keyData);
    }
}

public class MyChildForm : Form
{
    private MainForm mMainForm;

    public MyChildForm(MainForm mainForm)
    {
        mMainForm = mainForm;
    }

    // This is meant to forward accelerator keys (eg. Ctrl-Z) to the MainForm
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (mMainForm.ProcessCmdKeyFromChildForm(ref msg, keyData))
        {
            return true;
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}
like image 174
kostasvs Avatar answered Oct 11 '22 13:10

kostasvs