Pergunta

I'm building a customized virtual keyboard in C#.

The main point is sending a specific keypress to the window that currently has focus. But, normally, the key on the virtual keyboard will grab focus after it's pressed.

I'm assuming that some sort of Windows API should be used for this purpose. If so, which one, if not, what's the right way of doing it?

Foi útil?

Solução

Here's a good resource on this topic: http://www.yortondotnet.com/2006/11/on-screen-keyboards.html

Basically, create a form and use labels for the keys instead of buttons. You will need to override CreateParams to set the correct style. You must also override WndProc and filter out the messages that normally send focus to your form. Then add click events to your labels and use SendKeys.Send(keyPressed); to send the actual keystroke to the window with focus.

Here is the relevant code from the link:

    private const int WS_EX_NOACTIVATE = 0x08000000;

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams createParams = base.CreateParams;
            createParams.ExStyle = createParams.ExStyle | WS_EX_NOACTIVATE;
            return createParams;
        }
    }

    private const int WM_MOUSEACTIVATE = 0x0021;
    private const int MA_NOACTIVATE = 0x0003;
    protected override void WndProc(ref Message m)
    {
        //If we're being activated because the mouse clicked on us...
        if (m.Msg == WM_MOUSEACTIVATE)
        {
            //Then refuse to be activated, but allow the click event to pass through (don't use MA_NOACTIVATEEAT)
            m.Result = (IntPtr)MA_NOACTIVATE;
        }
        else
            base.WndProc(ref m);
    }

Outras dicas

I used panels (for keys) in a panel (The keyb) with a custom paint routine to draw the Text in center.

Click event is SendKeys.Send("1"); etc..

This was for a 10 key control, so hooking up events was pretty easy.

Didn't have to deal with any of the Window Messages, and it works good. I don't have any focus problems with the 10 key, and input gets sent where the cursor is. Simple.

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