473,383 Members | 1,925 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Type Casting

BRawn
28
I'm trying to cast types in an application a friend asked me to look at for him, but my casts aren't working. I want to cast from EventArgs to KeyEventArgs. Is this possible?

Here's the just of it:

Expand|Select|Wrap|Line Numbers
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4.       MainMenu_Key(sender, e);
  5. }
  6.  
  7. private void MainMenu_Key(object sender, EventArgs e)
  8. {
  9.       KeyEventArgs margs = (KeyEventArgs)e;
  10.       lbl_result.Text = margs.KeyCode.ToString();
  11.  
  12.       if (margs.KeyCode.ToString() == "D1")
  13.       {
  14.           if (tmrTIMER.Enabled == false && AvailableClicks != 0)
  15.       {
  16.           tmrTIMER.Enabled = true;
  17.           NextKeyToPress = 1;
  18.       }
  19.       KeyToPress = NextKeyToPress;
  20.       AvailableClicks -= Clickdeduction;
  21.       Actions += 1;
  22.       KeyPressed = 1;
  23.  
  24.       #region ///colorchange\\\
  25.       if (KeyPressed == KeyToPress)
  26.       { CorrectClick = 1; }
  27.       else { CorrectClick = 0; }
  28.       #endregion
  29.       if (CorrectClick == 1)
  30.       {
  31.           pb_1.Visible = false; }
  32.           pbColors(sender, e);
  33.       }
  34. }
  35.  
  36.  
I'm getting an InvalidCastException on line 9 (KeyEventArgs margs = (KeyEventArgs)e;) which I understand but is there another way to cast EventArgs to KeyEventArgs? I'm not too sure about the inheritance of types this way...
Aug 29 '11 #1

✓ answered by GaryTexmo

Ah I see what you're looking for. Yea the KeyPressEventArgs has a key char, which is the actual character the user pressed. KeyDown and KeyUp use KeyEventArgs, which give you a bit more information. However, it should work for you... here's an example.

Expand|Select|Wrap|Line Numbers
  1. public partial class Form1 : Form
  2. {
  3.     public Form1()
  4.     {
  5.         InitializeComponent();
  6.  
  7.         this.KeyDown += new KeyEventHandler(Form1_KeyDown);
  8.     }
  9.  
  10.     void Form1_KeyDown(object sender, EventArgs e)
  11.     {
  12.         KeyEventArgs args = (KeyEventArgs)e;
  13.  
  14.         Console.WriteLine("Key down: " + args.KeyCode.ToString());
  15.     }
  16. }
If the cast wasn't working, I'd have to guess your friend was listening to a different event (you still haven't posted the code for this). Anyway, it's important to point out that this won't work for what your friend wants to do anyway. Those event handlers are for the control that initiates the event only. In this case, you will only get the event when the form itself is active and in focus.

In order to record APM, you'll need to globally monitor input, which can be done through Windows API calls. There's an article on CodeProject that will explain this.

http://www.codeproject.com/KB/cs/globalhook.aspx

A couple of things to mention though...

1) This gets pretty close to a key logger. You're basically trapping global keyboard and mouse input, so this kind of thing could be considered a little sketchy. Just a heads up.

2) I don't know what game your friend wants APM for, but I know SC2 has a built in one and APM is a common metric that people want. Google around and you might be able to find something that exists already. If not, or he/you just want to make it anyway, you're on the right track :)

3 1049
GaryTexmo
1,501 Expert 1GB
I think you need KeyPressEventArgs instead of KeyEventArgs.

I'm also not sure what event you're listening to... I don't see one named Key, so it has to be KeyUp, KeyDown, KeyPress, or KeyPreview... but I'm not sure which it is. Can you please clarify on that?

Also, you can only cast where the data makes sense and is related. In the actual method signature for the above mentioned events, they actually have a KeyPressEventArgs parameter. It looks like your friend has renamed that to take the more generic EventArgs object. That's fine, but be aware that while all KeyPressEventArgs objects are also EventArgs objects, not all EventArgs objects are KeyPressEventArgs objects.
Aug 29 '11 #2
BRawn
28
I tried with KeyPressEventArgs. KeyEventArgs has a KeyCode property and KeyPressEventArgs has a KeyChar property. I'm not too sure what the difference between these two properties are but I did try the KeyPressEventArgs way, and still it didn't work.

Even though his using the more generic EventArgs object, I think what his trying to achieve is monitor the keys pressed as this application monitors his APM (actions per minute) while playing games.

The named key in the code I posted in my initial question listens to KeyCode 'D1'. It's a value in the 'Keys' enumerator. I've tried on the main form's KeyUp event but the event never fired even though on form_load, I used the Focus() method to focus on the main form for the KeyUp event to fire, but I didn't have much luck in that department either.

As all the controls his trying to listen on are pictureBoxes, which don't have any sort or KeyEvents, I told him to use buttons...at least that way he can make it look the same and he'll have KeyEvents to play with :)
Aug 30 '11 #3
GaryTexmo
1,501 Expert 1GB
Ah I see what you're looking for. Yea the KeyPressEventArgs has a key char, which is the actual character the user pressed. KeyDown and KeyUp use KeyEventArgs, which give you a bit more information. However, it should work for you... here's an example.

Expand|Select|Wrap|Line Numbers
  1. public partial class Form1 : Form
  2. {
  3.     public Form1()
  4.     {
  5.         InitializeComponent();
  6.  
  7.         this.KeyDown += new KeyEventHandler(Form1_KeyDown);
  8.     }
  9.  
  10.     void Form1_KeyDown(object sender, EventArgs e)
  11.     {
  12.         KeyEventArgs args = (KeyEventArgs)e;
  13.  
  14.         Console.WriteLine("Key down: " + args.KeyCode.ToString());
  15.     }
  16. }
If the cast wasn't working, I'd have to guess your friend was listening to a different event (you still haven't posted the code for this). Anyway, it's important to point out that this won't work for what your friend wants to do anyway. Those event handlers are for the control that initiates the event only. In this case, you will only get the event when the form itself is active and in focus.

In order to record APM, you'll need to globally monitor input, which can be done through Windows API calls. There's an article on CodeProject that will explain this.

http://www.codeproject.com/KB/cs/globalhook.aspx

A couple of things to mention though...

1) This gets pretty close to a key logger. You're basically trapping global keyboard and mouse input, so this kind of thing could be considered a little sketchy. Just a heads up.

2) I don't know what game your friend wants APM for, but I know SC2 has a built in one and APM is a common metric that people want. Google around and you might be able to find something that exists already. If not, or he/you just want to make it anyway, you're on the right track :)
Aug 30 '11 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: maxim vexler | last post by:
in a book i am ready now : O'Reilly - Web Database Application with PHP and MySQL, 2nd ed. by David Lane, Hugh E. Williams on chapter 9 the author give an example for age validation :...
5
by: Suzanne Vogel | last post by:
** Isn't the 'static_cast' operator the same as traditional type casting? ie, Aren't the following ways of getting b1, b2 the same? // 'Derived' is derived from 'Base' Derived* d = new...
1
by: JohnK | last post by:
under the covers is type casting in VB.Net the same as C# ? myObject = CType(..,..) in VB.Net vs myObject = (SomeClass)aObject
1
by: chook | last post by:
Wherein differences between type casting in C++ : static_cast, dinamic_cast, reinterpret_cast, const_cast and C type casting, like xxx = (type)yyy; What, when and why is necessary to use?
9
by: Roman Mashak | last post by:
Hello, All! Given the sample piece of code I have: #include <stdio.h> #include <string.h> int main(void) { short int i, j;
7
by: Wayne M J | last post by:
I have worked out most type casting and the likes but I am curious about one aspect. Endpoint ep...; IPEndPoint iep...; .... ep = (EndPoint)iep; .... iep = (IPEndPoint)ep; ....
23
by: René Nordby | last post by:
Hi there, Is there anyone that knows how to do the following? I have a class A and a class B, that 100% inherits from class A (this means that I don't have other code in class B, than...
16
by: Enekajmer | last post by:
Hi, 1 int main() 2 { 3 float a = 17.5; 4 printf("%d\n", a); 5 printf("%d\n", *(int *)&a); 6 return 0; 7 }
7
by: Ben R. | last post by:
How does automatic type casting happen in vb.net? I notice that databinder.eval "uses reflectoin" to find out the type it's dealing with. Does vb.net do the same thing behind the scenes when an...
11
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? ...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.