Low level keyboard input from Windows - winapi

What win32 calls can be used to detect key press events globally (not just for 1 window, I'd like to get a message EVERY time a key is pressed), from a windows service?

You want to use Win32 Hooks. In particular a keyboard hook.
You can read more about it here
The type of hook you want is WH_KEYBOARD and you can set it via the Win32 API SetWindowsHookEx.
Basically windows will call a function in a dll that you create everytime a key is pressed in any application system wide.
The hook will call your function which will have this interface:
LRESULT CALLBACK KeyboardProc(
int code,
WPARAM wParam,
LPARAM lParam
);
More information about this callback here.
With windows hooks you can not only track system wide events across all processes, but you can also filter them and stop them altogether.

Take a look at the hooks you can set with SetWindowHookEx:
http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx
However, unless you are running an "interactive" service, you won't have access to the desktop (and you shouldn't be running an interactive service because it won't work right in newer versions of Windows). You will have to look into the session and desktop management APIs in order to access the desktop/console.

Check out the Raw Input API in MSDN:
http://msdn.microsoft.com/en-us/library/ms645536(VS.85).aspx
It allows you to get input from keyboards (among other things) without messing around with global hooks. Global hooks should only be used as a last resort as they may introduce unintended consequences.
The only drawback to using Raw Input is that it may not properly receive keystrokes which are generated by software.

Just use the native function GetKeyState, or GetAsyncKeyState, or GetKeyboardState from user32 DLL.
You can read about each function I mentioned above in the msdn site:
h ttp://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
for the GetKeyState, and
h ttp://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx
for the GetAsyncKeyState, and
h ttp://msdn.microsoft.com/en-us/library/windows/desktop/ms646299(v=vs.85).aspx
for the GetKeyboardState.
If you program in C# then:
Your code must include the following line out of any class, struct or enum declaration:
using System.Runtime.InteropServices;
Then in the class that has the method where you want to detect the keys, define one of three functions above for your choice, or what works and what not.
[DllImport("user32.dll")]
static uint GetKeyState(byte virtualKeyCode);
//or
[DllImport("user32.dll")]
static uint GetAsyncKeyState(byte virtualKeyCode);
//or
[DllImport("user32.dll")]
static uint GetKeyboardState(byte[] virtualKeyCodes);
//NOTE: The length of the byte array parameter must be always 256 bytes!
If you dislike uint as return type, you can also change it to int.
If the native functions always return 1 as true or 0 as false, then you can change their return type to bool instead, but if you do so, then I think you should add another line of code above the native function definition, which is:
[MarshalAs(UnmanagedType.Bool)]
OR you can add the following line in the middle of the native function definition (below the line where the DllImport word is, and above the line, where the 'extern' word is):
[return: MarshalAs(UnmanagedType.Bool)]
Pinvoke site offers better definition for these functions, so you don't have to use integers to mention a particular key of your keyboard, but more understandable enum.
The following link leads to the definition of the GetKeyState in C#:
h ttp://www.pinvoke.net/default.aspx/user32.getkeystate
The following link leads to the definition of the GetAsyncKeyState in C#
h ttp://www.pinvoke.net/default.aspx/user32.getasynckeystate
The following link leads to the definition of the GetKeyboardState in C#
h ttp://www.pinvoke.net/default.aspx/user32.getkeyboardstate
To detect which key is held down (at any time, anywhere) then call GetKeyState or GetAsyncKeyState function, in the single parameter, mention the key you want to detect and then add: & 0x8000, or & 0x80 after the call.
If the mentioned key is held down, then the return value of the expression is not zero, but otherwise it is zero.
According to the returned integer of the expression, you can determine which key held down or not.
Note that if you put code inside if statement with that expression != 0 as enter condition, which is inside a loop, the code in that if statement will be executed more than once, actually many times, when you held down that key. If you want some code to be executed once When you press a key and then release it, then the following code is a trick that achieves this goal:
while (boolean exression that will return false when you want to quit this loop)
{
if (boolean expression that will return true when particular key is **held down**) //This boolean expression calls either GetKeyState or GetAsyncKeyState with the & 0x8000 or & 0x80 after the call, and then != 0 to check for **held down** key
while (true) //It's purpose is to wait for the same key that was held down to be released. After code execution, it will encounter the break keyword that will finish him, even though that his enter condition is true.
if (boolean expression that will return true when the **same** particular key is **NOT** held down! (NOT held down, means that at that time, that key was released). You can copy the same condition from the first if statement, and just change **!=**, which is next to 0, to **==**, or instead add brackets to the condition '(' and ')', and in left of '(' add '!').
{
//Put here the code that you want to execute once, when paticular key was pressed and then released.
break; //the while (true), which is the only way to get out of it
}
}

If you are implementing this in a .net application i'd recommend GlobalKeyboardHook, Otherwise i'd look at it's source and take what you need since it is implementing the DLLImport functions mentioned above.

Related

Is it possible for VariantClear to crash software if VariantInit is not called beforehand?

I have an exception that I cannot easily replicate, but I have a very strong suspicion that it happens during VariantClear().
I have a function that defines a variant and then passes it off to another variant without calling VariantInit() on it first. The called function then calls VariantClear() on this variant, which is the likely source of the exception.
void Func1()
{
VARIANT vData;
//VariantInit(&vData); // no variant clear was done. Will adding this line stop the crash below?
Func2(vData);
}
void Func2(VARIANT& vData)
{
// some code here
VariantClear(&vData); <-- this line crashes, why??
// some code here
}
Can anyone explain why VariantClear() could be throwing an exception? Will calling VariantInit() in Func1() stop this exception from happening?
VariantClear checks the first 16 bits of the VARIANT to find the variant type.
Depending on the type, VariantClear might call CoTaskMemFree or treat the variant as a COM pointer it calls Release on. If the type is invalid you might crash or free some unrelated memory.
If the type is VT_EMPTY, VT_NULL or a number type it just sets all fields to zero.
If you don't initialize the VARIANT, the type is undefined, it could be any value left in memory from a previous operation. Therefore you must call VariantInit first on the VARIANT.

Why Microsoft Error Message uses the word "Token"?

I purposely set a bad path for a CreateDirectory call so that my exception handling code would execute:
I am not sure if this is off topic, but you might have more experience with this. Why is the error text:
An attempt was made to reference a token that does not exist.
Why are they using the word token instead of file or folder?
I will close the question if off topic.
The return value of GetLastError is: 123
According to here:
ERROR_INVALID_NAME
123 (0x7B)
The filename, directory name, or volume label syntax is incorrect.
Now that message makes sense. So why is my Windows 10 showing the other message?
There is no issue with the call to FormatMessage. It works as advertised. However, you aren't passing in the value 123 (ERROR_INVALID_NAME). You are passing 1008 (ERROR_NO_TOKEN), by accident, due to calling GetLastError at the wrong time. GetLastError has a strong requirement:
You should call the GetLastError function immediately when a function's return value indicates that such a call will return useful data. That is because some functions call SetLastError with a zero when they succeed, wiping out the error code set by the most recently failed function.
It's fairly straightforward to satisfy this in C. With C++, things get more complicated, with all the invisible code the compiler generates. The code in question apparently captures the calling thread's last error code only after it enters the CWin32FileError c'tor. That's too late.
Based on the assumption that GetWorkingPath() returns a CString instance by value, and CWin32FileError takes its arguments as CString const&, this is what happens behind the scenes:
if (!CreateDirectory(GetWorkingPath() + _T("whatever"), nullptr))
GetWorkingPath() constructs a temporary CString instance.
operator+(CString const&, LPCTSTR) constructs yet another temporary CString instance, concatenating both inputs.
operator LPCTSTR() is implicitly invoked on the temporary constructed in step 2.
CreateDirectory is called and returns.
Important: The destructor of the temporary created in step 2 is called.
Important: The destructor of the temporary created in step 1 is called.
Steps 5 and 6 are fatal already, potentially changing the calling thread's last error code. And yet, there's even more code getting in the way:
CWin32FileError e(_T("whatever"),
GetWorkingPath() + _T("whatever"));
Important: _T("whatever") triggers CString's conversion constructor (CString(LPCTSTR)), producing a temporary.
Important: GetWorkingPath() constructs a temporary, invoking CString's copy-c'tor.
Important: operator+(CString const&, LPCTSTR) constructs yet another temporary.
The CWin32FileError c'tor finally runs, presumably calling GetLastError.
This adds another 3 candidates (at least) that can modify the calling thread's last error code. To solve this, you're going to have to make sure, that absolutely no code runs in between a failed Windows API call and the call to GetLastError.
To do this, you're going to have to get rid of the temporaries, and move capturing of the last error code outside the CWin32FileError c'tor. A simple solution to the former would be to construct the path name up front, e.g.
auto path_name{ GetWorkingPath() + _T("whatever") };
auto path_name_strptr{ path_name.GetString() };
if (!CreateDirectory(path_name_strptr, nullptr))
// ...
(or use an init-statement in the if statement to limit the scope, if you are using C++17). Either way, your very next call must be GetLastError to capture the last error code while it is still meaningful. However you pass that value into CWin32FileError's c'tor, or which argument types it uses, is up to you. But you cannot rely on that c'tor to capture the last error code for you.

What expressions are allowed in tracepoints?

When creating a tracepoint in Visual Studio (right-click the breakpoint and choose "When Hit..."), the dialog has this text, emphasis mine:
You can include the value of a variable or other expression in the message by placing it in curly braces...
What expressions are allowed?
Microsoft's documentation is rather sparse on the exact details of what is and is not allowed. Most of the below was found by trial and error in the Immediate window. Note that this list is for C++, as that's what I code in. I believe in C#, some of the prohibited items below are actually allowed.
Most basic expressions can be evaluated, including casting, setting variables, and calling functions.
General Restrictions
Only C-style casts supported; no static_cast, dynamic_cast, reinterpret_cast, const_cast
Can't declare new variables or create objects
Can't use overloaded operators
Ternary operator doesn't work
Can't use the comma operator because Visual Studio uses it to format the result of the expression; use multiple sets of braces for multiple expressions
Function Calls
Prohibited calls:
Lambdas (can't define or call them)
Functions in an anonymous namespace
Functions that take objects by value (because you can't create objects)
Permitted calls:
Member functions, both regular and virtual
Functions taking references or pointers, to either fundamental or class types
Passing in-scope variables
Using "&" to pass pointers to in-scope variables
Passing the literals "true", "false", numbers
Passing string literals, as long you don't run afoul of the "can't create objects" rule
Calling multiple functions with one tracepoint by using multiple sets of braces
Variable Assignment
Prohibited:
Objects
String literals
Permitted:
Variables with fundamental types, value either from literals or other variables
Memory addresses, after casting: { *(bool*)(0x1234) = true }
Registers: { #eip = 0x1234 }
Use Cases
Calling functions from tracepoints can be quite powerful. You can get around most of the restrictions listed above with a carefully set up function and the right call. Here are some more specific ideas.
Force an if
Pretty straightforward: set up a tracepoint to set a variable and force an if-condition to true or false, depending on what you need to test. All without adding code or leaving the debug session.
Breakpoint "toggling"
I've seen the question a few times, "I need to break in a spot that gets hit a lot. I'd like to simply enable that breakpoint from another breakpoint, so the one I care about only gets breaks from a certain code path. How can I do that?" With our knowledge above, it's easy, although you do need a helper variable.
Create a global boolean, set to false.
Create a breakpoint at your final destination, with a condition to break only when the global flag is true.
Set tracepoints in the critical spots that assign the global flag to true.
The nice thing is that you can move the tracepoints around without leaving the debugging session. Use the Immediate window or the Watch window to reset your global flag, if you need to make another run at it. When you're done, all you need to clean up is that global boolean. No other code to remove.
Automatically skip code
The EIP register (at least on x86) is the instruction pointer. If you assign to it, you can change your program flow.
Find the address of the line you want to skip to by breaking on it once and looking at the value of EIP, either in the Registers window or the Watch window with "#eip,x". (Note that the value in the Registers window is hex, but without the leading "0x".)
Add a tracepoint on the line you want to skip from, with an expression like {#eip = address}, using the address from step 1.
EIP assignment will happen before anything on the line is executed.
Although this can be handy, be careful because skipping code like this can cause weird behavior.
As Kurt Hutchinson says, string assignment is not allowed in a tracepoint. You can get around this by creating a method that assigns the string variable, and call that.
public static class Helper
{
public static void AssignTo(this string value, out string variable)
{
variable = value;
}
}
Then in your tracepoint message:
{"new string value".AssignTo(out stringVariable)}

Understanding MAKEINTRESOURCEW definition

Looking at the Windows SDK, I found this #define directive for MAKEINTRESOURCEW:
#define MAKEINTRESOURCEW(i) ((LPWSTR)((ULONG_PTR)((WORD)(i))))
Can someone explain to me what the heck that means? For example, what would be the value of MAKEINTRESOURCEW(0)? (1)? (-1)?
The result of this macro will be pointer to long string with value equal to given parameter. You can see it by reading precompiler output (see /P C++ compiler options). All casting is required to compile this macro result, when LP[w]WSTR pointer is required, both in Win32 and x64 configurations.
Some Windows API, like LoadIcon, expect string pointer as their parameter. Possibly, these functions test the pointer value, and if it is less than some maximum, they interpret it as resource index, and not as string (problems of ugly C-style interface). So, this macro allows to pass WORD as string, without changing its value, with appropriate casting.
For the most part, it leaves the value unchanged, but converts it from an int to a pointer so it's acceptable to functions that expect to see a pointer. The intermediate casts widen the input int to the same size as a pointer, while ensuring against it's being sign extended. In case you care, ULONG_PTR is not a "ULONG POINTER" like you might guess -- rather, it's an unsigned long the same size as a pointer. Back before 64-bit programming became a concern, the definition was something like:
#define MAKEINTRESOURCE(i) (LPTSTR) ((DWORD) ((WORD) (i)))
Nowadays, they use ULONG_PTR, which is a 32-bit unsigned long for a 32-bit target, and a 64-bit unsigned long for a 64-bit target.
That's a macro that casts an argument i to a word, then casts that result to a pointer to an unsigned long, then again to a long pointer to a wide-character string.
Like other users said - it just casts an integer into a "pointer to a string".
The reason for this is the following: At the ancient times of Windows 3.0 people tried to be minimalistic as much as possible.
It was assumed that resources in the executable can have either string identifier or integer. Hence when you try to access such a resource - you specify one of the above, and the function distinguish what you meant automatically (by checking if the provided "pointer" looks like a valid pointer).
Since the function could not receive a "variable argument type" - they decided to make it receive LPCTSTR (or similar), whereas the actual parameter passed may be integer.
Another example from Windows API: A pointer to the window procedure. Every window has a window procedure (accessed via GetWindowLong with GWL_WNDPROC flag.
However sometimes it's just an integer which specifies what "kind" of a window is that.
Then there's a CallWindowProc which knows to distinguish those cases.

General programming - calling a non void method but not using value

This is general programming, but if it makes a difference, I'm using objective-c. Suppose there's a method that returns a value, and also performs some actions, but you don't care about the value it returns, only the stuff that it does. Would you just call the method as if it was void? Or place the result in a variable and then delete it or forget about it? State your opinion, what you would do if you had this situation.
A common example of this is printf, which returns an int... but you rarely see this:
int val = printf("Hello World");
Yeah just call the method as if it was void. You probably do it all the time without noticing it. The assignment operator '=' actually returns a value, but it's very rarely used.
It depends on the environment (the language, the tools, the coding standard, ...).
For example in C, it is perfectly possible to call a function without using its value. With some functions like printf, which returns an int, it is done all the time.
Sometimes not using a value will cause a warning, which is undesirable. Assigning the value to a variable and then not using it will just cause another warning about an unused variable. For this case the solution is to cast the result to void by prefixing the call with (void), e.g.
(void) my_function_returning_a_value_i_want_to_ignore().
There are two separate issues here, actually:
Should you care about returned value?
Should you assign it to a variable you're not going to use?
The answer to #2 is a resounding "NO" - unless, of course, you're working with a language where that would be illegal (early Turbo Pascal comes to mind). There's absolutely no point in defining a variable only to throw it away.
First part is not so easy. Generally, there is a reason value is returned - for idempotent functions the result is function's sole purpose; for non-idempotent it usually represents some sort of return code signifying whether operation was completed normally. There are exceptions, of course - like method chaining.
If this is common in .Net (for example), there's probably an issue with the code breaking CQS.
When I call a function that returns a value that I ignore, it's usually because I'm doing it in a test to verify behavior. Here's an example in C#:
[Fact]
public void StatService_should_call_StatValueRepository_for_GetPercentageValues()
{
var statValueRepository = new Mock<IStatValueRepository>();
new StatService(null, statValueRepository.Object).GetValuesOf<PercentageStatValue>();
statValueRepository.Verify(x => x.GetStatValues());
}
I don't really care about the return type, I just want to verify that a method was called on a fake object.
In C it is very common, but there are places where it is ok to do so and other places where it really isn't. Later versions of GCC have a function attribute so that you can get a warning when a function is used without checking the return value:
The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug, such as realloc.
int fn () __attribute__ ((warn_unused_result));
int foo ()
{
if (fn () < 0) return -1;
fn ();
return 0;
}
results in warning on line 5.
Last time I used this there was no way of turning off the generated warning, which causes problems when you're compiling 3rd-party code you don't want to modify. Also, there is of course no way to check if the user actually does something sensible with the returned value.

Resources