tags:

views:

222

answers:

3

I am currently working on an application which requires different behaviour based on whether the user presses the right or left shift key (RShiftKey, LShiftKey), however when either of these keys is pressed I only see ShiftKey | Shift.

Is there something wrong with my keyboard? (laptop) do I need a new keyboard driver/keyboard in order to send the different key commands maybe...

This is a pretty massive problem at the moment, as there is no way of testing that the code works (apart from unit tests). Anyone had any experience of the different shift/alt/ctrl keys?

A: 

I don't know if this post will help you or not, but it looks like you may have to mess with InteropServices and Diagnostics:

MSDN Forum: How to send Left/Right shift key

Edit: I finally figured out how to make GetAsyncKeyState() work, as adrianbanks revealed.

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern short GetAsyncKeyState(Keys vKey);

private void theForm_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.ShiftKey)
    {
        if (Convert.ToBoolean(GetAsyncKeyState(Keys.LShiftKey)))
        {
            Console.WriteLine("Left");
        }
        if (Convert.ToBoolean(GetAsyncKeyState(Keys.RShiftKey)))
        {
            Console.WriteLine("Right");
        }
    }
}
JYelton
Hi - yeah I look at this post before but it only talks about sending the key stroke. What's odd is that the keyboard itself simply never sends this "Keys". So I assume I need to modify something in Windows to allow my keyboard to support this, or get a new driver, or both.
Mr AH
+2  A: 

Take a look at the GetAsyncKeyState Win32 method. You can add a pInvoke call to it using:

[DllImport("user32.dll")]
private static extern short GetAsyncKeyState(Keys key);

and then handle the KeyDown event on your form:

private void MyForm_KeyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine("Left Shift :  " + (GetAsyncKeyState(Keys.LShiftKey) < 0));
    Console.WriteLine("Right Shift: " + (GetAsyncKeyState(Keys.RShiftKey) < 0));
}
adrianbanks
This works, I finally worked out a similar solution also.
JYelton
A: 

Thanks guys, good solution there. In the mean time here's my own "hacky" way of doing it from the override of ProcessCmdKey:

public override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (msg.LParam.ToInt32() == 0x2a0001)
        LastShiftKey = ShiftKeys.NumericShift;
        else if (msg.LParam.ToInt32() == 0x360001)
            LastShiftKey = ShiftKeys.AlphaShift;
    etc....
}
Mr AH