Windows store apps c# - capslock on/off - c#

I have managed to determine if capslock is on or off, so that I can display proper error message. But my code works only, if capslock is off when textbox gets focus. But if it is on, then error message appears when it shouldn't.
private Boolean CapsLock = false; //here...how to determine if it is on or off propperly
private void loginCredentials_KeyUp(object sender, KeyRoutedEventArgs e)
{
switch (e.Key.GetHashCode())
{
//...
case 20:
CapsLock = (CapsLock) ? false : true;
errorMessage.Text = (CapsLock) ? ((App)(App.Current)).loader.GetString("capslockError") : String.Empty;
break;
}
}

The WinRT method to find the current key status is GetKeyState, so you can check the key value directly if you need to (similar to the IsKeyLocked mentioned in comments).
I'd note that switching on the hashcode of the key pressed seems wrong, you should check the key value itself against the code from the VirtualKey enum (I guess you've noticed that the hash code is just this value, meaning that it works).
If you do need to know immediately when a key such as the caps lock is pressed in general, not just when your text field has focus, you can register a key handler on the application root visual. Normally key presses will be consumed by controls like a text box that handle them, but you can use AddHandler with true parameter to listen to all key presses including handled ones, something like:
Window.Current.AddHandler(UIElement.KeyUpEvent, new KeyEventHandler(...), true);
Or alternatively use the Window.Current.CoreWindow.KeyUp event.

Related

SendInput events don't get processed in specific UI area of game

I have a C# application which sends keyboard and mouse events to a game. In the game there's a small UI portion which can change based on what we want to see (like GPS map, different actions to take etc). Sometimes in this portion of the UI we have to press 'Enter' (or another key depending on how the user configured the game's keys) to activate something (for example, press Enter to activate Rescue service).
Now , the problem: all the key events sent from the c# app are processed fine OUTSIDE of this UI, except this 'activate' thing. At first I thought there's a problem with the 'ENTER' (Return) key event, but after chaning it to another key that was working in-game, I noticed that key is also ignored.
I am not sure if it's a problem related to the way I send the messages (maybe it needs to have a specific parameter) and it can be fixed by modifying my app, or is some blockage in-game - and in this case there's nothing I can do.
Here's the code I use to send the key events:
public static void PressKey(short key)
{
INPUT[] inputs = new INPUT[]
{
new INPUT
{
type = INPUT_KEYBOARD,
u = new InputUnion
{
ki = new KEYBDINPUT
{
wVk = (ushort)0,
wScan = (ushort)key,
dwFlags = KEYEVENTF_SCANCODE,
dwExtraInfo = IntPtr.Zero,
}
}
},
new INPUT
{
type = INPUT_KEYBOARD,
u = new InputUnion
{
ki = new KEYBDINPUT
{
wVk = (ushort)0,
wScan = (ushort)key,
dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP,
dwExtraInfo = GetMessageExtraInfo(),
}
}
}
};
SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
}
But hoping its the 1st case, I would appreciate any help with this.
Added a screenshot in order to try to better explain the issue
(A) -> That is the UI window that requires "ENTER" to be pressed. Let's suppose that I modify the settings of the game to have "E" instead of "Enter" for the ACTIVATE action. Then the text "Call Assistance Service (ENTER)" will now show "Call Assistance Service (E)". By default, the "E" key is engine start in the game. And it works just fine (in the case (B)) . As soon as I change E to be 'Activate' , it's being completely ignored.
Another point which might (or might not) be relevant , is that the F-keys that can be at the bottom of the UI Window, also WORK just fine.
I hope this clears up the things a little bit more.
I have found what the issue was, and I'm pretty sure it's related to how the game handles the input (but since it's not me who coded the game I cannot guarantee it).
Anyway, to fix my issue, a delay needs to be added between the KEYDOWN and KEYUP events. For the time being I'm using a Timer with a callback for that, but probably there are other ways to do it also (better or not).
Hope this will help someone someday :)

multiple keys keydown on keyboard at once time in c#

I have an application which want to detect multiple keys on Keyboard (keydown event in c#).
In the last, i have limited keys detection (may be 4 keys) on event keydown and also i can't fire the event when "fn" keys keydown.
there are 2 question here:
1. How to detect keys as many as possible
2. How to detect Fn keys when keyboard keydown event.
Here, I us globalKeyboardHook library that i found from others solution.
private void Form1_Load(object sender, EventArgs e)
{
gkh.HookedKeys.Add(Keys.A);
gkh.HookedKeys.Add(Keys.B);
gkh.HookedKeys.Add(Keys.D);
gkh.HookedKeys.Add(Keys.F);
gkh.HookedKeys.Add(Keys.G);
gkh.HookedKeys.Add(Keys.H);
gkh.HookedKeys.Add(Keys.J);
gkh.HookedKeys.Add(Keys.K);
gkh.HookedKeys.Add(Keys.L);
gkh.HookedKeys.Add(Keys.Z);
gkh.HookedKeys.Add(Keys.X);
gkh.HookedKeys.Add(Keys.C);
gkh.HookedKeys.Add(Keys.V);
gkh.HookedKeys.Add(Keys.B);
gkh.HookedKeys.Add(Keys.N);
gkh.HookedKeys.Add(Keys.M);
gkh.HookedKeys.Add(Keys.Q);
gkh.HookedKeys.Add(Keys.W);
gkh.HookedKeys.Add(Keys.E);
gkh.HookedKeys.Add(Keys.R);
gkh.HookedKeys.Add(Keys.T);
gkh.HookedKeys.Add(Keys.Y);
gkh.HookedKeys.Add(Keys.U);
gkh.HookedKeys.Add(Keys.I);
gkh.HookedKeys.Add(Keys.O);
gkh.HookedKeys.Add(Keys.P);
gkh.HookedKeys.Add(Keys.NumLock);
gkh.HookedKeys.Add(Keys.Insert);
gkh.HookedKeys.Add(Keys.FinalMode);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
}
void gkh_KeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine(e.KeyCode.ToString());
e.Handled = true;
}
I am really pleasure, if you can help me.
thanks.
You can't get a KeyDown event with multiple keys.
However, you can either check for keys that are currently pressed, or you can keep track of all those that are Down at the moment (record them when you get KeyDown and remove when you get KeyUp).
There is a fixed limit to keys being pressed simultaneously based on the hardware keyboard. It may very well be that some key combinations only allow you to register two keys simultaneously, while others are more useable. And of course, there's gaming keyboards that can easily keep track of 20 or more at a time.
There is a managed library MouseKeyHook as nuget which has support for detecting shortcuts, key combinations and sequences. Source code on github. Here is a usage example:
void DoSomething()
{
Console.WriteLine("You pressed UNDO");
}
Hook.AppEvents().OnCombination(new Dictionary<Combination, Action>
{
{Combination.FromString("Control+Z"), DoSomething},
{Combination.FromString("Shift+Alt+Enter"), () => { Console.WriteLine("You Pressed FULL SCREEN"); }}
});
For more information see: Detecting Key Combinations and Seuqnces

How to detect if any key is pressed

How can I detect if any keyboard key is currently being pressed? I'm not interested in what the key is, I just want to know if any key is still pressed down.
if (Keyboard.IsKeyDown(Key.ANYKEY??)
{
}
public static IEnumerable<Key> KeysDown()
{
foreach (Key key in Enum.GetValues(typeof(Key)))
{
if (Keyboard.IsKeyDown(key))
yield return key;
}
}
you could then do:
if(KeysDown().Any()) //...
If you want to detect key pressed only in our application (when your WPF window is activated) add KeyDown like below:
public MainWindow()
{
InitializeComponent();
this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
}
void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("You pressed a keyboard key.");
}
If you want to detect when a key is pressed even your WPF window is not active is a little harder but posibile. I recomend RegisterHotKey (Defines a system-wide hot key) and UnregisterHotKey from Windows API. Try using these in C# from pinvoke.net or these tutorials:
Global Hotkeys: Register a hotkey that is triggered even when form isn't focused.
Simple steps to enable Hotkey and ShortcutInput user control
Thse is a sample in Microsoft Forums.
You will use Virtual-Key Codes.
I Hope that I was clear and you will understand my answer.
Iterate over the System.Windows.Input.Key enum values.
public static bool IsAnyKeyDown()
{
var values = Enum.GetValues(typeof(Key));
foreach (var v in values)
if (((Key)v) != Key.None && Keyboard.IsKeyDown((Key)v)
return true;
return false;
}
Good answer here...get the set of all the keystates at once using GetKeyboardState():
Detect if any key is pressed in C# (not A, B, but any)
The above is checking the live state of the keyboard.
If you rely on hooking events up to the KeyDown/KeyUp events to track the state of the keyboard...then this may not be so accurate.
That's becuase you are relying on the message pumping to process and dispatch those KeyDown/KeyUp messages....they may be delivered after the real keyboard state has changed again.
Also because when your bit of code that is interested in the keyboard state is running (usually on the UI thread)...the KeyDown or KeyUp can't interrupt you...as they are dispatched on the UI thread too....that's why using GetKeyBoardState() or the Keyboard.IsKeyDown should be used.
(the above is assuming you want and care about the live state)

Monitoring keyboard activity in C# while my application is in the background

First of all I need to make it clear that I have no interest in keylogging.
I need a way to monitor keyboard activity at the most basic level while my application is in the background.
I don't need to know which keys, I don't need to save any data, I don't need or plan to hide my application at all, all I need is to know when keys are pressed and invoke a method.
I'm looking for the simplest way to do this possible, I know a reasonable amount of C# but nothing too complex as most of my knowledge is self-taught.
I've looked around for some appropriate ways of doing this and I've found nothing useful. All I've found is a bunch of people saying "No, that's illegal" on forums and source code for in depth keyloggers.
If any of you could advise me on a way to achieve this then I would be most appreciative.
You'll need to use Window Hooks:
Low-Level Keyboard Hook in C#
But beware, Windows security, may be protecting us from doing what you want!
You can monitor keyboard and mouse activity in the background with the Nuget package MouseKeyHook (GitHub).
This code detects when a key is pressed:
private IKeyboardMouseEvents _globalHook;
private void Subscribe()
{
if (_globalHook == null)
{
// Note: for the application hook, use the Hook.AppEvents() instead
_globalHook = Hook.GlobalEvents();
_globalHook.KeyPress += GlobalHookKeyPress;
}
}
private static void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
{
Console.WriteLine("KeyPress: \t{0}", e.KeyChar);
}
private void Unsubscribe()
{
if (_globalHook != null)
{
_globalHook.KeyPress -= GlobalHookKeyPress;
_globalHook.Dispose();
}
}
You will need to call Subscribe() to start listening, and Unsubscribe() to stop listening. Obviously you need to modify GlobalHookKeyPress() to do useful work.
I needed this functionality in order to write a utility which will turn on the keyboard backlight on a Lenovo Thinkpad when any key is pressed, including CTRL (which KeyPress doesn't catch). For this purpose, I had to monitor for key down instead. The code is the same except we attach to a different event...
_globalHook.KeyDown += GlobalHookOnKeyDown;
and the event handler signature is different:
private static void GlobalHookOnKeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("KeyDown: \t{0}", e.KeyCode);
}
The library can also detect specific key combinations and sequences. For example:
Hook.GlobalEvents().OnCombination(new Dictionary<Combination, Action>
{
{ Combination.TriggeredBy(Keys.A).Control(), () => { Console.WriteLine("You Pressed CTRL+A"); } },
{ Combination.FromString("Shift+Alt+Enter"), () => { Console.WriteLine("You Pressed FULL SCREEN"); } }
});
Microsoft tells you How to: Handle Keyboard Input at the Form Level. As long as you handle the same event(s) this works for any non web application.
You should also take a look at the other questions here on SO, such as Handling Input from a Keyboard Wedge
You could register Windows Hot Key with RegisterHotKey windows API, look at this blog post :
http://www.liensberger.it/web/blog/?p=207

Equivalent of PreviewKeyDown of C# needed for native C++/MFC

I used a ActiveXControl in a C# Forms application and had the possibility to implement a PreviewKeyDown event handler for that ActiveXControl. That was needed to specify that, e.g. the [ALT] key, is an input key.
For some reasons or other I have to reimplement the application in native C++/MFC and don't know how to specify that this [ALT] key is an input key and to be handled by the ActiveXControl.
You could use SetTimer to generate a WM_TIMER event 20 times a second or so
SetTimer( NULL, kMyTimer, 50, MyTimerCallback );
Then implement a function as follows.
void CALLBACK MyTimerCallback( HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime )
{
static short lastLeftAltPress = 0;
short thisLeftAltPress = GetAsyncKeyState( VK_LMENU );
if ( thisLeftAltPress != 0 && lastLeftAltPress == 0 )
{
CallAltHandlingCode();
}
thisLeftAltPress = lastLestAltPress;
// Handling code for other keys goes here.
}
This will then poll the keyboard every 50ms to find out if the left alt key has just been pressed and then call your handling code. If you want to fire the handler when its released then you would use the following if statement
if ( thisLeftAltPress == 0 && lastLeftAltPress != 0 )
or if you just want to see if it is down then you do
if ( thisLeftAltPress != 0 )
The docs for GetAsyncKeyState do state that you can check whether the lowest bit is set to see if the key has just been pressed but it does also point out that this may fail in unexpected ways in multi-threaded environments. The above scheme should always work.
thanks for all your recommendations.
For my case I finally found some way how to make it work. So far what I have learnt the situation is that a PreviewKeyDown event is triggered before the KeyDown message is sent.
I implemented PreTranslateMessage in the dialog which hosts the ActiveX control and called ::SendMessage(WM_KEYDOWN...) with the handle of the ActiveX control, using pMsg for the arguments.
Cheers,
Ilmari
I think that you can use the GetAsyncKeyState Win32 function (http://msdn.microsoft.com/en-us/library/ms646293%28VS.85%29.aspx) to get the state of all the keys in the system, VK_MENU (http://msdn.microsoft.com/en-us/library/dd375731%28v=vs.85%29.aspx) is the key you should monitor for the [Alt] key.
Haven't tried this, but MSDN doesn't say that you won't get a WM_KEYDOWN for the ALT key -- any other key pressed while ALT is down generates a WM_SYSKEYDOWN, but that doesn't say that you can't handle ALT via WM_KEYDOWN.

Categories

Resources