views:

80

answers:

4

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?

+2  A: 

I think it is because KeyCode.ToString() doesn't return what you expect it to return. Look at the view in a Watch.

Snake
Actually log wasn't showing any difference but when i copied it from my log file and pasted in here it seems there's new line after Oemtilde so by using .Trim() it works. Thanks.
MadBoy
+1  A: 

another change make use of string.Equals function to compare string

string1.Equals(string2)
Pranay Rana
A: 

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.

Dan Iveson
Article suggest to == for strings: "So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings - comparing strings with == does make things an awful lot simpler and more readable but you need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly." just one needs to be careful.
MadBoy
A: 

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.

Scott Lance
It's returning string if you convert it to string. If you press F1 it will show F1 if you press ` you will get Oemtilde etc. I had new line which is weird it is there.
MadBoy