Reputation: 11104
I'm using this library to hook keys and I have some problems with comparing e.KeyCode.ToString() with same string.
I have variable which is string equivalent of
Keys.Oemtilde
->
Program.KeyboardTradeHotkey = "Oemtilde";
I keep it in string because I read that string from xml file and I can't seem to get any way to convert string to Keys
.
If i use it this way:
if (e.KeyCode.Equals(Keys.Oemtilde)) {
Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
} else {
// failed to catch - executes else
Logging.AddToLog("[Keyboard][PRESS]");
}
It works fine and: Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
is executed.
If i use it:
if (e.KeyCode.ToString() == Program.KeyboardTradeHotkey) {
Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
} else {
// failed to catch - executes else
Logging.AddToLog("[Keyboard][PRESS]");
}
It executes else clause. It seems like String Compare doesn't really works in this case even thou both string (e.KeyCode.ToString() and Program.KeyboardTradeHotkey are the same.
What can be the reason for this?
Upvotes: 0
Views: 7112
Reputation: 936
The difference between == and .Equals() is because of the differences between reference types and value types. This link gives examples of the different results: Comparison of == and .Equals()
I also agree with pranay_stacker.
Upvotes: 0
Reputation: 2249
Without having to look at the library that you are using the first (working) code sample looks like it is comparing enum values, so it is returning a number instead of a string.
Upvotes: 0
Reputation: 176886
another change make use of string.Equals function to compare string
string1.Equals(string2)
Upvotes: 4
Reputation: 8116
I think it is because KeyCode.ToString() doesn't return what you expect it to return. Look at the view in a Watch.
Upvotes: 3