I have a WinForm application where I need to capture a KeyPress and fetch the scancode for it. Along with that I need to convert existing scancodes int key names (by converting to virtual keys beforehand perhaps?) Is there any way to accomplish this?
The first part is possible, but tricky, because multiple Virtual Key (VK) codes will map to the same scancode (depending on the keyboard shift/ctrl/alt state).
I'm not sure what you mean by "key name," but if you're referring to the physical keyboard layout then, for your next step, you will need to make some assumptions about the key's location based on standard physical keyboard layouts (101-key, 102-key etc).
See my answer to this question for some sample code and a more detailed description.
If you still need it, you can use Reflection for private members access. I know it's not good idea and interfaces can change in next versions, but it works for .Net Framework 4.6
private void OnKeyDown(object sender, KeyEventArgs e)
{
MSG l_Msg;
ushort l_Scancode;
PresentationSource source = e.InputSource;
var l_MSGField = source.GetType().GetField("_lastKeyboardMessage", BindingFlags.NonPublic | BindingFlags.Instance);
l_Msg = (MSG)l_MSGField.GetValue(source);
l_Scancode = (ushort)(l_Msg.lParam.ToInt32() >> 16);
//Use scancode
}
Related
I've got an Entry control on my Xamarin application home page, which is used for entering a person's age. I've set the keyboard to be Keyboard="Numberic"
However, this is causing confusion as, for Android at least, the "Done" key is below backspace, but above the settings key as well as the .- key. This means when the user is trying to press "Done", they're forgetting that the key isn't in the bottom right-hand corner as you'd expect, and they keep pressing the settings key by mistake and going into their phone settings, which is a bit irritating, understandably.
Is it possible to either disable the settings key and the .- key, or swap their positions around? I'm not expecting it to be possible, so in which case, is there another way that I can get around this?
Screenshot to clarify what I mean - can the keys with the settings cog and the ".-" be moved or disabled, to prevent the user opening their phone settings and putting negative/decimal numbers in?
I have not used C# in a bit and never with Android but the idea of removing characters from a String is most languages is normally simple enough.
Based on our small discussion in the comments, and a little research; I believe this is what you are looking for to strip unwanted values from the EditText field where the user's input goes in your application:
var editText = FindViewById<EditText> (Resource.Id.editText);
editText.TextChanged += (object sender, Android.Text.TextChangedEventArgs et) => {
//step 1 grab editText value
String newString = et.Text.ToString();
//step 2 replace unwanted characters (currently '.' & '-')
newString = newString.Replace(".", "").Replace("-", "");
//step 3 set the editText field to the updated string
editText.Text = newString;
};
Resource:
https://github.com/xamarin/recipes/tree/master/Recipes/android/controls/edittext/capture_user_input_text
I have not found a way to change the default keyboard for Android so you can remove unwanted keys (i.e. the settings key) or reorder them, so I am still thinking if you decide that you must do this, you would need to build a custom keyboard for the application.
I'm writing a VNC client for HoloLens using C# and I'm having a tough time figuring out how to handle keyboard input. KeyUp/KeyDown give me a Windows.System.VirtualKey object, but there doesn't appear to be an API to map these VirtualKeys (along with modifiers, e.g. shift) to the characters they represent on a given layout. E.g. VirtualKey.Shift + VirtualKey.F == 'F' versus 'f' when it's simply VirtualKey.F. Or Shift + 5 to give % on a US keyboard.
In win32 apps you'd use MapVirtualKey to handle the keyboard layout for you -- how does this get handled in UWP?
It is not possible to get the translated character in KeyUp/KeyDown events. But it is possible when using CoreWindow.CharacterReceived event to get the translated character.
You can register the event by the following codes:
Window.Current.CoreWindow.CharacterReceived += CoreWindow_CharacterReceived;
And you will get a KeyCode of the translated input character(e.g. for shift+5 it gets 37, while for 5 it gets 53) through the CharacterReceivedEventArgs:
private void CoreWindow_CharacterReceived(CoreWindow sender, CharacterReceivedEventArgs args)
{
uint keyCode=args.KeyCode;
}
I found this gem (IMO) in System.Windows.Forms namespace. I'm struggling to figure out why is it set like this.
[Flags]
public enum MouseButtons
{
None = 0,
Left = 1048576,
Right = 2097152,
Middle = 4194304,
XButton1 = 8388608,
XButton2 = 16777216,
}
Can somebody explain why it uses these values (power of 2^20 to 2^24) instead of this:
public enum MouseButtons
{
None = 0,
Left = 1, // 2^0
Right = 2, // 2^1
Middle = 4, // 2^2
XButton1 = 8, // 2^3
XButton2 = 16, // 2^4
}
The first value is 100000000000000000000 in binary, which leaves space for another 20 bits! Why do we need such space and why is it preserved like this?
Enum values used in Winforms do tend to match corresponding bits in the winapi but that's not the case at all for mouse buttons. Explaining this one requires a pretty wild guess.
I do have one, the way you retrieve the state of the mouse buttons without relying on a Windows message is very strange. You call GetAsyncKeyState(), passing VK_LBUTTON through VK_XBUTTON2. Fake virtual keys that actually represent mouse keys and not keyboard keys. This happened way too long ago for me to guess why they did it this way instead of providing a proper GetMouseButtonState() winapi function.
The Keys enumeration has those values as well, like Keys.LButton etcetera. Something else that's special about Keys is that it can also encode the state of a modifier key. There are for example Keys.Control and Keys.ControlKey. And Keys.Shift vs Keys.ShiftKey, etcetera. The first one indicates the state of the key, the second one indicates the actual key. Which permits friendly code like keydata == (Keys.Control | Keys.F) to check if Ctrl+F was pressed.
The significance of these MouseButtons enum values is then that they fit in a Keys enum value to indicate the state of the mouse buttons. Leaving 20 bits available for the bits that encode the key.
Sounds good, doesn't it? The only hiccup is that it is never combined that way within the Winforms object model. But could be in your own code to define a shortcut that also uses the mouse state.
My guess is that it has to do with how the underlying Windows API is passing mouse information to .NET.
Windows packages up which mouse buttons are clicked as well as pointer position in a block of information (think of the old MOUSE_EVENT structure). The enums in .NET are setup the way they are to be efficient, so they probably line up nicely with how the underlying Windows message.
So, instead of getting the lower-level message and having to convert it into a new set of values, .NET just targets the bits in the lower-level message that it is interested in - no conversion, no math, just efficiency.
How can we simulate CTRL+V keys (paste) using C#?
I have a textbox that hasn't a id for access, for example textbox1.Text = someValue won't work here.
I want to fill that textbox (from clipboard) by clicking on it. For some reasons we exactly need simulate CTRL+V, mean we cannot use external libraries like inputsimulator.
Character vs key
% => alt , + => shift and ^ is used for ctrl key
Original Answer:
Simulation of single modifier key with another key is explained below
Step1: Focus the textBox, on which you want to perform two keys and then Step2: send the key for example control-v will be sent like "^{v}". Here is the code
target_textBox.Focus();
SendKeys.Send("^{v}");
target_textBox.Focus(); is needed only when target textbox is not focused at the time of sending key
Update: For sending three keys (two modifying keys plus other key) like to achieve ctrl shift F1 you will send following
^+{F1}
Microsoft Docs Ref
Why don't you override the TextBox OnClick event than when the event is called, set the Text property to Clipboard.GetText()
Like:
private void textBox1_Click ( object sender, EventArgs e )
{
textBox1.Text = Clipboard.GetText ();
}
This function is already built in: TextBoxBase.Paste()
textbox1.Paste();
some JS do not permit to change value in usual way
inputList[21].SetAttribute("value", txtEMail.Text);
you should try something like this:
inputElement.InvokeMember("focus");
inputElement.InvokeMember("click"); //sometimes helpfull
Clipboard.SetDataObject(txtEMail.Text);
SendKeys.Send("^(v)");
//but not "^{v}"
In case the language in the operating system is not English, this option may not work:
SendKeys.Send("^{v}");
Then try this option:
SendKeys.Send("+{INSERT}");
I was asked this question by a friend, and it piqued my curiosity, and I've been unable to find a solution to it yet, so I'm hoping someone will know.
Is there any way to programatically detect what type of keyboard a user is using? My understanding of the keyboard is that the signal sent to the computer for 'A' on a DVORAK keyboard is the same as the signal sent to the computer for an 'A' in a QUERTY keyboard. However, I've read about ways to switch to/from dvorak, that highlight registry tweaking, but I'm hoping there is a machine setting or some other thing that I can query.
Any ideas?
You can do this by calling the GetKeyboardLayoutName() Win32 API method.
Dvorak keyboards have specific names. For example, the U.S. Dvorak layout has a name of 00010409.
Code snippet:
public class Program
{
const int KL_NAMELENGTH = 9;
[DllImport("user32.dll")]
private static extern long GetKeyboardLayoutName(
System.Text.StringBuilder pwszKLID);
static void Main(string[] args)
{
StringBuilder name = new StringBuilder(KL_NAMELENGTH);
GetKeyboardLayoutName(name);
Console.WriteLine(name);
}
}
that probably depends on the OS. I'm sure that there is an operatingsystem setting somewhere that registers the nationality of the keyboard. (Dvorak is considered a nationality because French keyboards are different from US keyboards are different from ...)
Also, just a side note: 'A' was a bad example, as 'A' happens to be the same key in dvorak and qwerty... B-)
You might be able to do it via DirectInput, or whatever the current DirectX-equivalent is. I type on a Dvorak keyboard, and about 50% of the games I buy detect my keyboard and reconfigure the default keymappings to support it (using ,aoe instead of wasd, for instance)
And yes, as Brian mentioned, 'A' is the same on both keyboards.
Why would it matter? Depending on some special implementation of a keyboard is no good idea at all. We use barcode scanners all over the place that emulate keyboard inputs. What would your program do with these devices? :)
PS: the mentioned registry entry arranges the keys of a regular keyboard into dvorak layout.