Reputation: 31
I am in the process of converting a project from Visual Basic .Net to C#; I have been able to figure out most of the differences and get the code working but I'm running into snags such as the following code snippet:
private void rtbSend_KeyDown1(object sender, KeyEventArgs e)
{
if (e.KeyCode == 17)
{
blnCtrlKey = true;
}
}
When I try to compile, I get the error in the subject line; what puzzles me is that the values for KeyCode should already be int, so the error makes little sense to me. Can anyone point me in the right direction? I'd like to have the program this code will be include in working by mid-April.
Upvotes: 3
Views: 1647
Reputation:
Also You can Use Convert
Class to solv your Problem like below code
private void rtbSend_KeyDown1(object sender, KeyEventArgs e)
{
if (Convert.ToInt32(e.KeyCode) == 17)
{
blnCtrlKey = true;
}
}
Upvotes: 1
Reputation: 216363
No, the KeyCode property of the KeyEventArgs parameter passed to the KeyDown event is of type Keys (an enum).
In C# you cannot rely on the compiler/language to convert from one type to another type for you. Use appropriate casting or conversion when you compare value or, better, use the correct type.
private void rtbSend_KeyDown1(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ControlKey)
{
blnCtrlKey = true;
}
}
Related to your situation, I wish to signal that the current state of the Control key is already available in the Control property of the KeyEventArgs, so using this property is better if you need to test a key combination IE: CTRL + N
private void rtbSend_KeyDown1(object sender, KeyEventArgs e)
{
// Control is pressed with the N key
if (e.Control && e.KeyCode == Keys.N)
{
.....
}
}
Upvotes: 7
Reputation: 48736
Steve's answer is the better answer and the correct one. I only wanted to point that it is possible to cast an enum
to an int
(assuming its an integer enum):
private void rtbSend_KeyDown1(object sender, KeyEventArgs e)
{
if ((int)e.KeyCode == 17)
{
blnCtrlKey = true;
}
}
Like I said, this is not a good solution. It makes your code difficult to read. Keys.ControlKey
is a lot clearer than 17
. But I just wanted to point out that enumerations can be cast to its integer equivalent.
Upvotes: 2