Click here to Skip to main content
15,896,481 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am new to C# and not up to speed with OOP.

I am converting a TurboC program to Windows.

The old program used a global variable to store user key srokes.
The C# prog has a static variable for the same purpose.
This is updated by an overriden OnKeyDown.

However on entering a method, called via a form menu, key strokes are ignored.

I fear it is something fundamental in my approach.
Suspect not grasping change from procedural programming.

Can anyone point me in the right direction.

Thanks
Posted
Comments
OriginalGriff 27-Oct-10 7:46am    
What are you doing in your method? Are you looping and waiting for the static variable to change?
Because if you are, it won't.
Toli Cuturicu 27-Oct-10 9:14am    
Fake answer by OP converted to this comment:
Thank you OriginalGriff.
I am and it isn't.
Solution or guidance?
Thanks
Keith Barrow 27-Oct-10 9:16am    
He's kinda given you the answer, the loop is blocking the keystrokes. It'd be better raise an event when you update the static variable.

1 solution

I think you need to set the KeyPreview property to True to get all keystrokes.

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.aspx[^]

If you mean that your method executes for quite some time, then this means that the message loop that deals with application messages (like a keystroke) isn't handled. If it would take to long, you would also get the "(not responding)" in the taskmanager.

You could execute your method in a thread. The most basic way to do this is:
using System.Threading;
// ...
new Thread (new ThreadStart (SomeObject.SomeMethod)).Start();


The code above doesn't maintain a reference to the thread, but it's just a simple example.

Here is some extra reference:
http://www.yoda.arachsys.com/csharp/threads/[^]

http://www.yoda.arachsys.com/csharp/threadstart.html[^]

It is also important to know that Invoke must be used if you would like to do some screen updating from a thread:
http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx[^]

Some info on how to control the thread:
http://msdn.microsoft.com/en-us/library/7a2f3ay4%28VS.80%29.aspx[^]

You could also do without threads and bloat your methods with an excessive amount of Application.DoEvents(); to ensure the message loop is handled. This is however quite dangerous and error prone. Every save person will advise against the use of this hack... so, be warned!

Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900