Best way to handle input from a keyboard "wedge" - c#

I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key presses that contain the card swipe sentinel characters.
Is there a better way to deal with this sort of input?
Edit: The device does simply present the data as keystrokes and doesn't interface through some other driver. Also We use a wide range of these types of devices so ideally a method should work independent of the specific model of wedge being used. However if there is no other option I'll have to make do.

One thing you can do is that you should be able to configure your wedge reader so that it presents one or many escape characters before or after the string. You would use these escape characters to know that you are about to have (or just had) a magcard input.
This same technique is used by barcode reader devices so you application knows to get focus or handle the data input from the device.
The negative to this approach is that you have to properly configure your external devices. This can be a deployment issue.
This assumes that your devices simply present the data as keystrokes and don't interface through some other driver.

You can also use the Raw Input API if you know the Hardware IDs of the devices ahead of time. I blogged about this recently. It may be insane but it satisifed my requirement: the primary goal in my case was to be able to receive input even when the application lost focus because someone accidentally bumped into something while rummaging around to scan items on a pallet. The secondary goal is that I couldn't add any sentinel characters because that would have broken existing third-party applications being used with the scan guns.
I've done the sentinel character method before, however, both via a KeyPress attach or a low-level keyboard hook via SetWindowsHookEx() or via KeyPreview on your application's main form. If it meets your requirements, it's definitely much simpler and easier to use that method and to that end I second the recommendations already given.

I think you are handling it in an acceptable way, just be careful of how fast the card sends the data, we have wireless bar code scanner's, and now and again they throw the key strokes at the keyboard to fast for the application to handle.
also if you are distributing your software to other territories, then key stokes may be different, for example in Spain (I think, but may be France) the top line of the keyboard is !"£$%^&() opposed to the USA/UK 1234567890, and if your card reader is set to usa/uk then it will send !"£$%^&() in place of 1234567890, as the wedge just emulates that key been pressed and if windows interprets it different then its your problem.

Another vote for jttraino's idea. I do much the same with card-readers and cheque-readers in point-of-sale systems where we need to support keyboard wedge as well as USB and RS232.
Basically, choose a short sequence of characters unlikely to come from the keyboard, and program your message handling loop to see these characters arriving. If you get a completed stream of characters that match your pattern, you can decode the rest of your input until you hit your designated 'end' sequence, or until you decide the incoming sequence is in error. Select a string that is either difficult, or impossible, to enter from the regular keyboard into your app given things like edit masks and the behaviour of your various screens.
A good starting point is something like tilda-pling (~!) as those characters are not likely to appear in anyone's personal details and not likely to ever need to appear together in the text of a note, etc. :-)
The downside, exactly as jttraino said, is that you will probably have to configure/program each reader device itself. Some manufacturers make this fairly easy to do - whose kit are you using? Magtek? Welch Allyn?

I second #jttraino's idea.
It is the way to go for bar scan/code readers and other such devices that are plug and play (PnP). I have used the same technique to configure a couple of 1D and 2D bar code scanners in my previous assignment.

Related

How do I use a device exclusively in my c# application?

First of all no I'm not writing a keylogger... what I have is a barcode scanner that appears as a keyboard... well I need a way to use the scanner exclusively... this app will run in the background so I need ALL scanned data to scan into my app regardless of what app I'm using..
my guess is to make an invisible form that pops up and has focus when I pull up the screen that I need the barcode scanned..
Please take a look at my answer here How HID devices work when programming?
You can set up your scanner to function as a USB-HID device and capture PDF417 scanned data.
Don't know if you need to do anything special. From what I have worked in the past, scanners are not much more than a keyboard wedge device. Whatever field you are in, scan and as long as a simple barcode (code 39, code 128, similar) that are not complex, they should just fill in whatever field you are on.
Now, that being said, if you have a 2d barcode (PDF417), or other complex barcode that has capacity of larger amounts of data, special characters, etc., that you may need to do parsing, that goes an extra level.
If you could also provide maybe the specific device / manufacturer, there might be libraries that you can use to pre-capture the data and parse before sending forward.
FEEDBACK per comment.
I had to do a similar option of licenses, but limited states needed. Only a few states actually provide their specific format. Doing hospitality work, you probably need to cover most states, and probably skip over international and require that.
Also, having to push the results into whatever current app is, currently active, you might be able to capture in the background and push a Windows message of the final decoded to the active application. May need to dig into those API calls more directly.. Good luck, but I'll try to look into possible messaging for you too.

How to intercept each trying to use API function in C#?

i need to block any screen capture software on the computer from taking screen shots. Since all of them are work on standard API-functions, i think i could monitor and block them.
I need to use C#.
All i have found is how to monitor and block them in a certain program (screen capture program). They are looking for a function in the program, then they change it address on mine function address.
But how can i do it, if i haven't any certain programs? I need to block anyone which tries to take a screenshot.
If your final goal is possible or not I don't know, but for the hooking the API portion I can help you out.
I have used the library EasyHook many times in the past, this will let you hook and intercept system function calls from C# code fairly easily. Just read through the PDF tutorial for setup instructions.
For actually finding the API's I recommend Rohitab's API Monitor, it's still in Alpha stages but it works really well and is free. You just hook it on to a processes and it tells you every external DLL call it makes (with the parameters it passed if you have the xml definition file for the DLL, the program comes with almost all of the windows API dll's pre-defined).
The combination of EasyHook and API Monitor is a great 1-2 punch for mucking with other program's calls.
It is not possible to prevent screenshots from being taken. The battle is already lost because of the DWM (Desktop Window Manager). It's lower level than Win32 and device contexts.
If you want to protect the text in your program, there are a lot easier ways to extract it than doing screenshots and OCR. TextOut and/or Direct2D hooking and accessibility APIs.
If there's a lot of IP in your program. Then don't make it all available onscreen. Make sure it's tedious to crawl the GUI for text, and hard to automate it. And don't load whole texts in memory of the program.
Possible solutions:
1. To prevent copying of text. Draw the text as an image.
2. To prevent accessibility technologies, like screen readers - override WndProc in your control, handle and ignore the window message WM_GETOBJECT.
3. To make it harder if they try to use OCR. Draw graphics behind the text. Human readable, but much harder for a machine to interpret it.
Neither of these methods are invasive for the user.
** A very invasive suggestion **:
If you are really serious about preventing anyone from "stealing" your content.
Implement mouse and keyboard hooks. Filter out typical copy shortcuts. Prevent the mouse from leaving the boundaries of your application.
Allow your application to only run when the OS runs well-known processes and services.
If any process starts which you don't recognize, black out the application and notify the user about it, and request the user to close it. And ofc make sure someone is not just spoofing a well-known process.
Monitor the clipboard as you suggested yourself.
You can ofc soften some of these suggestions based on the context of your application.
As Scott just posted it likely can be prevented with API hooks to see that paint events only go to desktop bound handles and not others, and refuse to paint otherwise. However, you need to consider the following scenarios and see if they're relevant threat to your approach or not:
Your software may be running in a virtual machine like VMWare. Such software has capapbilities to capture screen that does so at "virtual hardware" level, and your API hooks will not be able to discern it - and this would be the easiest way approach if I wanted to bypass your protections.
As a post suggests here, nothing also prevents someone to take monitor cable and plug it into another computer's capture card, and take screenshot that way. Again, your hooks will be helpless here.
Bottom line, you can make it somewhat harder to do, but bypassing such protection may be pretty trivial thing to do.
My 2c.

Intercept and cancel key press events for DirectX game

I'm working on a small tool for a DirectX game and I want to prevent the user from pressing a certain key (F12 in this case) for a certain period.
I could find many options for simulating keypresses but what are the options when it comes to nulling out a keystroke before the game reads it?
The language doesn't really matter, although I would prefer a C# or C++ solution, or just a nudge in the right direction :)
Thanks in advance!
The good news is, I've done this before so I can say that it is possible and it does work.
The bad news is that it's not simple. It requires a lot of complicated code, and will likely take a long time to implement, but I'll explain how you can do it.
Applications like DirectX games usually register for raw input.
Since you want to stop a keyboard event from reaching the application, you need a way to insert your code between the raw input and the game so you can check the raw input and decide whether to allow it to be passed to the game:
So you want to change the flow from:
Raw Input --> Game
to
Raw Input --> Your Code --> Game
Without having access to the source code of the game, you have to find a way to insert your code.
When there is keyboard input available, the game will call the WinAPI function GetRawInputData, which will tell it about the keyboard event. Ideally, what we want is when the game calls this function, it actually calls our code instead of the WinAPI function. Then we can decide what to tell the game about the keyboard event, we could tell it anything we want (e.g. ignore F12). Sounds great right? Here's where it gets interesting...
We can take advantage of how windows loads executables into memory. Typically, a program uses (or 'imports') calls to functions in other DLLs (such as GetRawInputData, in User32.dll). When the program gets loaded into memory, Windows will fill in a table (the Import Address Table (IAT)) with pointers to the executable code in the appropriate DLLs. This means that when the program calls the function, it gets directed to the executable code in User32.dll in memory to run it.
Wouldn't it be great if we could write/patch the address of one of our functions into that table, so that when the game calls GetRawInputData, it actually gets directed to our function for us to process? Well we can! It's called Import Address Table Patching.
There's a pretty good article on it here with some working code in C++. You should first read it to understand in more detail how it works, then you can modify it to support your needs. It will work, but I know it's probably more work (much more work) than you would have been hoping for, but essentially you're hacking the application which is never easy to do.
It's worth doing, even just to gain a better understanding of Windows behind the scenes.
Good luck!
EDIT
As Simon said, Windows Hooks is a much simpler way to do it if the game isn't using raw input. DirectX Games tend to be a special case that don't really work too well with standard Hooks as they use special methods to get the input from the user. By all means give it a go though, it will be a lot easier if it works.

Is there a way to get the raw data from a DVI port?

I have nopt seeing anyone else trying to do this. It is completely possible I am apperoaching this the wrong way. Basically, I have a computer with a DVI input. If nothing is attached to the DVI input, then a program on the computer loads some images on screen. If an output source is connected to the DVI port, then my program should stop writing images and use the DVI video feed instead.
What mechanisms exist to determine if a DVI input exists, and if there is currently a valid video signal present? How can I read the video stream?
Or am I going about this the completely wrong way?
At a hardware level most video input subsystems, analog or digital, are capable of detecting the presence of an input signal, or at least something that has a lot of the characteristics of one.
For a digital standard, you have actual clocking data either on its own wire, or encoded in a serial data stream. If there appears to be a clock, and if its frequency is regular and reasonable would be a first test (though for some standards, reasonable can cover a huge range of frequencies).
Next, video (not just digital, even analog) has a repeating structure of lines and fields, so there should be two identifiable submultiples of the pixel clock, one corresponding to the start or end of each line, and the other to the start or end of each field (screen). Again, these might have their own wires, might have unique means of encoding (special voltages in the analog case), or might represent time gaps in the pixel data. Even if there were no sync and no retrace times, statistical analysis of the pixel data would probably give clues to the X and Y dimensions as many features in the picture would repeat.
Actual video input subsystems (think flatpanel monitor) can have even more complicated detection and auto-adapting circuits - they may for example resample the input in time to change the dots-per-line resolution, or they may even put it in a frame buffer and scale it in both X and Y.
What details of the inner workings of the video capture circuit are exposed to consumer, or even driver level software would depend a lot on the specifics of the chipset used - hopefully a data sheet is available. It's pretty likely though that somewhere there is a readable register bit that indicates if the input is capturing something that the circuit "thinks" is a video signal. You might even be able to read out parameters such as the X and Y resolution and scanning rates or pixel clock rate.
Similarly, the ability to get data out of the port would be chipset dependent, but if the port is going to be useful for anything, there is presumably an operating system driver for it which provides some sort of useful API to video consuming applications.

"Symbol" brand barcode scanner and c#

I have a "Symbol" brand barcode scanner (USB) and I am trying to capture the data it scans from a barcode into my application (which is running as a service -- with no textbox control, of course).
The catch is that : Whenever you scan something, it acts like a keyboard and outputs the digits to anything that has focus (i.e notepad, word, etc).
My question is: How do I perform this barcode scan in the background and put it in a variable that I can use in my in C#.
So far, the only api's that I've found are for the .NET CF and I need this to be a
windows service.
Basically, I want to be able to send certain keystrokes to an application if the barcode = "123456789-0111" without interfering with the current window that has focus. After my application reads the barcode in then it will look for a certain program (launch it and set focus) and send keystrokes. I am using Code 128.
The HID mode will be your best best.
Put the barcode reader in HID mode and make your service capture the reader. When data comes in take a look at it and if it is one of your special barcodes you can act on it.
If the data is not one of your special barcodes then inject them as keydown/keyup windows messages so that it will seem to work in the same fashion as in keyboard emulation mode.
Put the scanner into USB mode. This is generally done by scanning a series of barcodes in your manual or printed out from the software provided from symbol.
With the scanner plugged in/docked connect to windows update. You'll get an update specific to that scanner. It won't work if if the scanner is not plugged in.
The scanner should map to a com port. This has typically been com 2 on the machines I've set it up on.
Download JustinIO. For my scanner, useful COM settings: Baud Rate: 9600, ByteSize 8, StopBits: 1 Parity: 0
Create a new CommPort instance. Set up a thread that does something like:
StringBuilder sb;
byte[] b;
do
{
b = commPort.Read(1);
sb.Append(Encoding.ASCII.GetChars(b));
Thread.Sleep(20); //symbol is slow...
} while(b.Length > 0);
Note: that's much crunched down from the code that I'm actually using so you'll need to modify it for your application.
Send the string to your application via whatever method seems appropriate.
The scanner is configured as HID (human interface device) and emulating keyboard.
To access it through Symbol's API, you probably have to disactivate current communication mode and set it to native one - should be documented in the scanner manual. Then you can access it directly without input field.
PS. I have no Symbol's scanner, but this is common to many devices.
It really depends upon the barcode scanner's api, and that is specific to the vendor. You'll need to get the the api for the scanner from the vendor, if you can't find it on their site you should just email their support, though you might find you have to buy the api.
First..
Ignore the .NET CF info for now as it probably pertains to the actual handheld unit. The mode of operation, pretending to be a keyboard, is referred to classically as a 'keyboard wedge'.
Second..
What kind of barcode symbologies are you attempting to use? And for what purposes? Or, mor directly,...What do the barcodes look like when scanned? (Do they contain special leading and trailing characters?)
Third... keep it simple... avoid the API unless it is necessary...
In the past when I've had to interface with barcode scanners, I've used a very simple approach in that my data entry form has the property of KeyPreview true and contains a method to detect and direct input originating from the scanner (by examining starting and trailing characters) to the appropriate control. Most of the scanners I've dealt with were programmable (usually via barcodes) to pass a custom set of characters to signal beginning and end of scanned input.
I hope that helps....
Here is a CodeProject sample that demonstrates how to set up global mouse and keyboard hooks in C#:
http://www.codeproject.com/KB/cs/globalhook.aspx
You could add this code to your console application, and then just monitor all keyboard input, looking for the specific codes you need. No API fuss or muss.

Categories

Resources