By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,145 Members | 1,688 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,145 IT Pros & Developers. It's quick & easy.

WPF Keyboard input UI thread issue?

Expert 100+
P: 464
I have a simple application which includes a default window (named Window1) with no additional xaml.

Window1 consists of a timerclass object which contains a timer running at 60hrz.

Expand|Select|Wrap|Line Numbers
  2. public Window1()
  3.         {//in Window1.xaml.cs
  4.             MainTimerClass = new TimerClass(); //my timer class object
  5.         }
The Timer class consists of an object which handles keyboard operations
Keyboard class is defined as below.

Expand|Select|Wrap|Line Numbers
  1.  class KeyboardHandle
  2.     {
  3.         public KeyboardHandle()
  4.         {
  5.         }
  7.         public void ProcessKeyboardEvent(ref Hashtable MappedKeyTable)
  8.         {
  9.             foreach (DictionaryEntry de in MappedKeyTable)
  10.             {
  11.                 Key TempKey = (Key)de.Key;
  12.                 if(Keyboard.IsKeyDown(TempKey))
  13.                 {
  14.                     int pq = (int)de.Value;
  15.                 }
  16.             }
  17.         }
The Timer calls the ProcessKeyboardEvent 60 times a second. When i hit the line of code Keyboard.IsKeyDown(TempKey)) i get the runtime exception "The calling thread must be STA, because many UI components require this"

Basically I want my code to check a given set of keyboard keys to see if they are pressed or not. I saw that the GUI element of WPF runs on a different thread and I have to use the Dispatcher.Invoke methods, but 1.) Why is the keyboard tied to a UI thread? two How can I use the dispatcher.Invoke to get the keyboard state? Any ideas on how to do this? I could just use windows hooks or Wnd_Proc, but I would prefer not to... Any ideas/suggestions? Let me know if you need anything else posted.
Jan 12 '10 #1
Share this question for a faster answer!
Share on Google+

Post your reply

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