How to pass keyboard accelerators from Axhost to containing .NET form

255 views Asked by At

I have an Activex control hosted inside a .NET form using Axhost as a wrapper. I've defined a shortcut key in the ProcessCmdKey method of the form, but when thye focus is inside the Activex, the keyboard messages and events are captured and not being handled by the ProcessCmdKey.

Here is my code:

public partial class Form1 : Form
{
    AxDirControlLib.AxDirList dirlist = null;

    public Form1()
    {
        InitializeComponent();
        this.KeyPreview = true;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dirlist = new AxDirControlLib.AxDirList();
        //dirlist.PreviewKeyDown += dirlist_PreviewKeyDown;            

        panel1.SuspendLayout();
        dirlist.BeginInit();
        panel1.Controls.Add(dirlist);
        panel1.ResumeLayout();
        dirlist.EndInit();
    }        

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.N))
        {
            MessageBox.Show("New project");
        }
        Console.Out.WriteLine("--------------MainForm---------");
        Console.Out.WriteLine(keyData);
        Console.Out.WriteLine("--------------MainForm---------");
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

I did manage to workaround it by using SendKeys from the PreviewKeyDown event handler of the Axhost, but it's messy and requires some focus shifting for it to work. Any suggestions?

1

There are 1 answers

2
noseratio On

Try also overriding Control.IsInputKey and watch for the keys you're interested to handle. If that doesn't work either, and you have no control over the ActiveX control source code, you could try to handle this situation using WinAPI's SetWindowsHookEx (KeyboardProc). The p/invoke signature is defined here.

[EDITED] To override IsInputKey, you'd need to derive a new class from AxDirControlLib.AxDirList and do it in that class. Then add an instance of that class to the form instead of AxDirControlLib.AxDirList.