سؤال

I am trying to get the keyboard state in my XNA application with the following code:

this.OldKeyboard = this.NewKeyboard;
this.NewKeyboard = Keyboard.GetState();
this.OldMouse = this.NewMouse;
this.NewMouse = Mouse.GetState();

However, sometimes (I think about 60%) when I start my game, I get an InvalidOperationException with the following message:

An invalid operation occurred when trying to query the keyboard state.
The result code was 126.

at Microsoft.Xna.Framework.Input.Keyboard.GetState(PlayerIndex playerIndex)
at Microsoft.Xna.Framework.Input.Keyboard.GetState()
at GameLib.GameBase.Update(GameTime gameTime) in MY_PATH\GameLib\GameLib\GameBase.cs:Line 58.
at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
at ...

My searches on google and SO did not give me any results on this code.

What could be the cause for this and why doesn't it occur everytime or never, but only sometimes when starting the project?

Edit: My thread layout:

  • Main thread
  • starts Game.Run
  • starts a network initializer in a separate project (in Initialize)
  • which starts a new thread for network I/O

When creating a new project only containing Keyboard.GetState(), I apparently get an error code of 0, which translates to

ERROR_SUCCESS

0 (0x0)

The operation completed successfully.

See my screenshot below, I do not know why a success would trigger an InvalidOperationException.

error code zero

هل كانت مفيدة؟

المحلول 2

I don't know how old this thread is, but I heard it has something to do with your firewall. The same error happened to me when I updated my antivirus (do you happen to use Comodo?) Anyway, check that out, and see if it helps. It has nothing to do with XNA, I tested in visual c# express, visual studio 2012, and 2013, with same results, then I tried with a fresh project that only called the keyboard state, and it happened again. And none of that happened before I updated the antivirus...

نصائح أخرى

Keboard.GetState uses the win32 function GetKeyboardState (MSDN) internally. If that fails, it gives an error code from this list, which XNA fetches and packs into that exception for you.

That error code translates to: "The specified module could not be found."

Where "module" basically means DLL. And "not found" might refer to the DLL being loaded, or a DLL that it, in turn, requires (and so on). It's an extremely unhelpful error message.

I'm not really sure what DLL GetKeyboardState might be trying to load, or why it might fail intermittently.

Probably the first step to try and fix this would be to create a new, blank project and see if you get the same result, so you can figure out if it's your code, or something wrong with your system or XNA install.

(I imagine actually debugging this properly might involve using Process Monitor to catch what DLL it is failing to load.)

Also, Blau is correct - all input in XNA must be done on the main thread.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top