Convert List of Windows.System.Virtualkey to String - c#

I'm creating an application which will capture a string from an USB attached scanner. I don't want a text box on the form I'm capturing the data on so I've added a handler to the KeyDown event of the window. There is a specific sequence of key presses I can look for to start capturing the data, however, what I can capture is a list of Virtualkeys. That would include LeftShift, v for 'V'
I'm looking for a way to take the array of Virtualkeys and convert that to a string.
Or if you can suggest another way to catpure the text, maybe hidden textbox?
UPDATE
I've positioned a textbox off window and was able to maintain keyboard focus on it so I could capture the data from the barcode scanner.

You can get info whether any VirtualKey is pressed using this:
bool isPressed = Window.Current.CoreWindow.GetKeyState(VirtualKey).HasFlag(CoreVirtualKeyStates.Down);
AFAIK this is the best way of getting to know whether more keys are pressed at the same time.

Related

Detect question mark independent from keyboard

The goal is simple: When the user enters chars in a textbox, I want to detect if this char is the question mark key (?).
I don't care what to use (text changed, key down etc...)
One thing to mention: I am working on a german keyboard layout and therefore I need a solution independent from the keyboard (for example: e.Key = Keys.OemQuestion isn't working, it fires when I press the plus (+) key)
Edit: I tried Convert.toString((char)e.Key) which returned \u0095 and e.Key.ToString() which returned OemOpenBrackets
I chose the solution from #HansPassant and managed to do it with the TextInput event.
First in the constructor:
InitializeComponent();
CommandTextBox.AddHandler(TextBox.TextInputEvent, new TextCompositionEventHandler(CommandTextBox_TextInput), true);
You need this code to actually fire the event
in TextInput
if(e.Text == "?")
{
//Do something
}
NOTE:
This does not capture space, control, shift etc.

Improve Barcode search in a Textbox C#

In a WinForm C# application I have a Barcode_textbox. In TextChanged event I have an SQL query to check for the TextBox.Text value in the database which is the barcode. The problem is that for each entered digit the SQL Query will be fired, so if a barcode of length 13 it will make 13 check in the database and it is being extremely SLOW.
So, what is the TextBox event that is fired only when the user stops writing in the TextBox (or the barcode reader stpos reading), or what is the optimal solution for checking for a barcode in the database. Note that bacode is of different length
I recall how I did this with success.
I put Timer control in my application with a Interval of a second (1000 milli's). Then I set the Form.KeyPreview property to True.
In the Form Key Press event I store the key strokes. In the Timer.Tick event check if the length of the recorded key strokes exceeds 12 or so characters.
Then fire off the call to SQL, once. When you return a record successfully (or if the textbox contains greater than say 20 chars) clear the stored key strokes.
See update, as at March 2019:
https://stackoverflow.com/a/55411255/495455
Timers are a horrible solution to this.
Use the KeyUp event of the TextBox and check for a carriage return. Most barcode scanners submit a carriage return after the code.. and if they don't do it by default, they come with barcodes to configure it to do so.
You can test this by opening Notepad and scanning barcode after barcode into it. Each one will be on a new line.
Use timer in this fashion that when user stops typing in your textbox for a given small time say 1 second only then get data from database...
Also you can place a check at the characters typed by user with a counter such that when it exceeds that minimum(the minimum size that your key can be) get the data...Will save much time
You could use the Validating event to check the content of the TextBox.
Your user will be required to press the TAB key to change the current focus from the TextBox to the next control following the taborder and the validating event will be triggered
private void textBox_BarCode_Validating(object sender, CancelEventArgs e)
{
// Code to check the barcode on the SQL database....
if(!ValidBarCode(textBox1.Text))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
}
}
Suppose that the next control is the command that executes something using the Barcode inserted (Add)(or a textBox to insert the quantity of the item described by the barcode). After a while all the operation becomes a very natural data entry processing
What about doing the query async?
If you can't or want an easy dirty solution, then I would just stick to the timer

Converting string obtained from database into keypress event

I have a string value in a variable. I want it to be thrown in keypress event.
When user clicks on "Start Writing Button". The text contained in variable gets written to the area whereever cursor has focus.
eg.
string str = "Example"
I have a web page with a textbox and a button. When user clicks on Start Reading button Example gets written on to textbox.
Basically the characters being written should be trapped on
javascript-onKeyPress event
Winform- KeyPress event
etc.
EDIT
I want to use some devices that will be throwing data constantly to my variable using window service. I need to write this data to the active window whereever the cursor has focus currently irrespective of window or web.
I copied data to clipboard and pasted on active window but this is problematic since different tabs are considered to same active window and doesn't writes.
Looking for a proper way rather then workaround I have taken.
Now that you've clarified the question, I suspect you want SendKeys.SendWait.
You'll need to be somewhat careful with it, but it may do what you want.

Is there a way to press or fireup the keys in key board using c# code?

I want the 'Alt' to be pressed by code. It is like firing key-press event with key 'Alt' by the code, not hitting it manually. The need is, I have set 'ShortCut keys for menu, but it (the single underline on key letter) is not visible to the user unless he presses 'alt'. So i need to make the Alt be pressed by default.
Is there a way to 'press' or 'fireup' the keys in key board using c# code?
Check out the System.Windows.Forms.SendKeys class.
You can use the static Send method to send keystrokes to the active window. If you're trying to send keystrokes to another window, you'll need to use the Windows API to activate the other window first.
If you have any control over the operating system on which the program is being deployed, apparently you can force the underlined shortcut letter to always be displayed by going to Control Panel -> Display -> Appearance -> Effects -> Hide underlined letters for keyboard navigation.
(http://www.chinhdo.com/20080902/underlined-letters-windows/)
here is a complete article on use of SendKeys on codeproject
Here is how you simulate input (both mouse and keyboard).
http://msdn.microsoft.com/en-us/library/ms171548.aspx
If you look at the System.Windows.Forms.SendKeys class you will see that it provides you with what you want.
http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx

Simulate keypress in a non-visible webbrowser object C#

I'm currently working in an application that has to navigate a webpage and recollect data about products, prices, ... with webbrowser object in .net 3.5.
The problem is that the page has some fields with a suggest script in ajax, and I can't simply modify the innerText property because the script also saves codes in a hidden input field.
I need a way to simulate the typing in that field and then send the "Enter" key, or launch the ajax script and then send the "Enter" key, or any better ways to do this.
Use Watin
Then you can use this solution.
To submit a form or run a script you can do this:
If you know the script name you can use InvoekScript of Document object:
myWebBrowser.Document.InvokeScript("script-name",null);
the second argument is an array of objects to pass parameters values.
if you know the name of an element that it's click event fires the script you can do this:
HtmlElement element=myWebBrower.Document.GetElementById("element-name")[0];
element.InvokeMember("click");
There are a few ways to do this with the standard WebBrowser control.
For HTML: If you want to fillout a textbox and then click submit then don't even bother with a keypress. Do this:
webbrowser1.Navigate("javascript:function%20E(){f0=document.forms[0];f0['login'].value='foo';}E()")
webbrowser1.Navigate("javascript:document.forms[0].submit()")
This will be much more reliable then trying to send keypresses for HTML.
**For Flash:**If there's a flash element on the webpage that needs clicking then it won't work. In that case SendKeys is reliable but only sends to the active application so it won't work in the background. You can send windows messages like this (example will press the letter "f"):
Dim c as char = "f"c
Dim classname As New System.Text.StringBuilder(100)
Dim ExplorerHandle As IntPtr = webbrowser1.Handle
GetClassNameA(ExplorerHandle, classname, classname.Capacity)
Do While classname.ToString <> "Internet Explorer_Server"
ExplorerHandle = GetWindow(GetExplorerHandle, GetWindow_Cmd.GW_CHILD)
GetClassNameA(ExplorerHandle, classname, classname.Capacity)
Loop
PostMessageA(ExplorerHandle, WM_Constants.WM_KEYDOWN, IntPtr.Zero, IntPtr.Zero)
PostMessageA(ExplorerHandle, WM_Constants.WM_KEYUP, CType(VkKeyScanA(CType(Asc(c), Byte)), IntPtr), IntPtr.Zero)
You can find the definitions for PostMessage, GetClassName, GetWindow, etc, online at pinvoke.net. Notice that the WM_KEYUP uses c but the WM_KEYDOWN sends a dummy key (0). KEYDOWN and KEYUP have to go in pairs or else the key won't be registered, but if you hold down Control while sending, for example, KEYDOWN "p", it will activate IE's print function. For all the letters and digits you can send 0 for KEYDOWN and the correct letter for KEYUP. Backspace seems to need a real KEYDOWN, not 0, but Control-Backspace doesn't seem to do much in IE so if c = vbBack, KEYDOWN needs to be different.
The keypresses aren't very accurate, either, and 1 time in about 500 it misses. But you can do it with the window minimized, no problem, and a standard WebBrowser control.
Another option is to use AxWebBrowser. The ActiveX control seems to avoid the Control-P problem but it's not as easy to manipluate because it isn't a nice .Net control.

Categories

Resources