Can an application block calls to SendInput? - winapi

There's a game that I'm trying to automate some actions on.
I've used SendInput in the past very successfully. However, with this application I can't get the mouse click to work. I've tested it using other applications and it all works as expected.
Can applications block my use of SendInput? And if so, can I get around it somehow?
Side note: I'm writing code in C# and running on Windows 7 x64. The app I'm trying to interact with is x86. I don't know if this makes a difference? I've testing my code interacting with both x64 and x86 apps.

Short answer: No. (Not the call to SendInput, but the input can be filtered. See update below.)
If you look at the parameters for SendInput there is nothing that identifies a process. The input is sent to the system, not an application. An application has no way of telling the difference between real and synthesized input.
There are a number of reasons why an application will not respond to synthesized input. As explained in the documentation for SendInput this API is subject to UIPI. An application running at a higher integrity level than an application calling SendInput will not receive this input.
Although SendInput injects input at a lower level than DirectInput runs, DirectInput is apparently more susceptible to buggy code. See Simulating Keyboard with SendInput API in DirectInput applications for reference.
Update (2016-05-01):
Besides issues with UIPI, preventing input from reaching an application, it is also possible for a low-level keyboard/mouse hook to identify injected input. Both the KBDLLHOOKSTRUCT (passed to the LowLevelKeyboardProc callback) as well as the MSLLHOOKSTRUCT (passed to the LowLevelMouseProc callback) contain a flags member, that have the LLKHF_INJECTED or LLMHF_INJECTED flag set, in case the input is injected.
An application can thus install a low-level keyboard/mouse hook to filter out messages that are injected. If this is the case, a potential workaround (without writing a keyboard driver) is, to install a low-level keyboard/mouse hook after the application did, and prevent input to reach the application's hook by not calling CallNextHookEx (hooks are called in reverse order they are installed, from last to first).
Note: The workaround is deliberately short-circuiting installed hooks, thereby likely breaking other applications. Besides, if an application decided to implement a low-level hook to filter out injected input, it may just as well guard against competing low-level hooks by frequently re-installing itself to the top of the hook chain, this rendering the workaround useless.

Related

For what is the function-like macro Yield() in winbase.h (line 97)?

There is a weird function-like macro in the header file winbase.h at line 97 as follows:
#define Yield()
For what is it?
Windows 3.x used cooperative multitasking model. All apps (also called "tasks") used to run in the same memory space on single thread. Usually, switching between tasks was performed by GetMessage API in the app's main message loop. Yield() used to be the way to voluntarily switch to another app (e.g., if doing a lengthy CPU-bound processing). Here's a related MSKB article which has still survived.
Of course, Yield() API like that doesn't make sense with the modern multi-threaded, multi-process OS architecture. So, Microsoft replaced it with an empty macro in attempt to achieve compile-level code compatibility.
Interestingly enough, in some form Yield() has been reincarnated in .NET 4.5. Its purpose is to defer the continuation of an asynchronous method on the current SynchronizationContext (or on a pool thread, if there is no synchronization context). The interesting part of that is, using Task.Yield() within the main UI thread of a .NET app actually allows to organize a similar level of cooperative multitasking Windows 3.x had to offer.

Can the console output of a Windows console application be captured fully (incl. advanced manipulations)?

It is a trivial matter of redirecting a console program's standard input/output, but what about if the program uses advanced console functions? Like outputting colored text, throwing the cursor around and manipulating the console buffer directly? Can that also be captured and redirected to my own program for processing?
Note: I'm talking about the scenario where my app (not necessarily a console app) runs a console app and redirects its input/output to itself.
Note 2: In the end I'll want C# code, but for now let's stick to bare Win32 API and C or C++. I don't think it will be possible without PInvoke anyway, so let's get the basic principle down first (if at all possible).
Unlike Linux, all color IO is not going to be captured with simple redirecting, so the only way to capture it is to hook on WinAPI calls (i.e. you will need to intercept system calls), which require administrative privileges, fragile and suspicious.

What is the difference between reading keyboard input asynchronously and using DirectInput?

DirectInput requires a lot of initialization functions and cetera to detect keyboard input, so what benefits are there to using it rather than the GetAsyncKeyState() function?
Courtesy of Wikipedia...
DirectInput and XInput have benefits over normal Win32 input events:
They enable an application to retrieve data from input devices even when the application is in the background.
They provide full support for any type of input device, as well as for force feedback.
Through action mapping, applications can retrieve input data without needing to know what kind of device is being used to generate it.
Basically DirectInput gives you more flexibility to move away from the keyboard. If the keyboard is all you ever plan on using then there is probably no harm in using GetAsyncKeyState()
Also see Should I use DirectInput or Windows message loop?
Microsoft seem to recommend just using windows messages to handle input data where possible now.

Can I put LowLevelMouseProc and LowLevelKeyboardProc in the main EXE?

Global Windows hooks must be in a DLL because the hook is going to be called in the context of a different process, so the hook procedure's code must be injected into that process. However, there are limitations:
SetWindowsHookEx can be used to inject
a DLL into another process. A 32-bit
DLL cannot be injected into a 64-bit
process, and a 64-bit DLL cannot be
injected into a 32-bit process. If an
application requires the use of hooks
in other processes, it is required
that a 32-bit application call
SetWindowsHookEx to inject a 32-bit
DLL into 32-bit processes, and a
64-bit application call
SetWindowsHookEx to inject a 64-bit
DLL into 64-bit processes. The 32-bit
and 64-bit DLLs must have different
names.
For this reason, I'd rather use the low-level hooks WH_MOUSE_LL and WH_KEYBOARD_LL, instead of WH_MOUSE and WH_KEYBOARD. As seen from their documentation:
This hook is called in the context of
the thread that installed it. The call
is made by sending a message to the
thread that installed the hook.
Therefore, the thread that installed
the hook must have a message loop.
This leads me to think that these particular hook procedures do not need to be in a separate DLL, and can just live inside the EXE that hooked them up. The documentation for SetWindowsHookEx, however, says:
lpfn
[in] Pointer to the hook procedure. If the dwThreadId parameter
is zero or specifies the identifier of
a thread created by a different
process, the lpfn parameter must point
to a hook procedure in a DLL.
No explicit exception for the two low-level hooks is mentioned.
I have seen several .NET applications that use the low-level hooks without having their hook procedures in a separate DLL. That is another hint that this is acceptable. However, I'm a bit scared to do this myself since the documentation forbids it.
Does anyone foresee any trouble if I don't use a DLL and just put these low-level hook procedures straight into my EXE?
Edit: For the bounty, I would like a definitive "yes, this is ok, because..." or "no, this can go wrong, because...".
Turns out that this is actually in the documentation. Although not in the documentation of SetWindowsHookEx and friends, but in a .NET knowledge base article.
Low-level hook procedures are called on the thread that installed the hook. Low-level hooks do not require that the hook procedure be implemented in a DLL.
There is one exception to the global hooking function in dll rule. Low level mouse and keyboard hooks are executed in the context of the calling process, not the process being hooked (internally, Windows notifies your hook via a windows message). Therefore the hook code is not executed in an arbitrary process and can be written in .Net. See http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx for an example.
For other hooks you do need to call the 32 bit version of SetWindowsHookEx and pass a hook function in a 32bit process and call the 64bit version of SetWindowsHookEx and pass a hook function in a 64bit process, though.
Global hooks, whether low or high level, have to be in a separate DLL that can be loaded into each process. The documentation you quoted makes that pretty clear, and if there was an exception that applied to the low-level hooks, that documentation would say so as well.
Rule of thumb: When the docs say not to do something, there's usually a pretty good reason for it. While it may work in some cases, that fact that it works may be an implementation detail, and subject to change. If that happens, then your code will be broken if the implementation is ever modified.
Edit: I take back my previous answer. It turns out that WH_MOUSE_LL and WH_KEYBOARD_LL are exceptions to the usual rule about global hooks:
What is the HINSTANCE passed to SetWindowsHookEx used for?

Low-overhead I/O monitoring on Windows

I would like a low-overhead method of monitoring the I/O of a Windows process.
I got several useful answers to Monitoring certain system calls done by a process in Windows. The most promising was about using Windows Performance Toolkit to get a kernel event trace. All necessary information can indeed be pulled from there, but the WPT is a massive overkill for what I need and subsequently has a prohibitive overhead.
My idea was to implement an alternative approach to detecting C/C++ dependency graphs. Usually this is done by passing an option to the compiler (-M, for example). This works fine for compilers and tools which have such an option, but not all of them do, and those who do often implement them differently. So, I implemented an alternative way of doing this on Linux using strace to detect which files are opened. Running gcc (for example) in this way has a 50% overhead (ballpark figure), and I was hoping to figure out a way to do this on windows with a similarish overhead.
The xperf set of tools have two issues which prevents me from using them in this case:
There is no way to monitor file-I/O events for a single process; I have to use the kernel event trace which traces every single process and thus generates huge amounts of data (15Mb for the time it takes to run gcc, YMMV).
As a result of having to use the kernel event trace, I have to run as administrator.
I really don't need events at the kernel level; I suppose I could manage just as well if I could just monitor, say, the Win32 API call CreateFile(), and possibly CreateProcess() if I want to catch forked processes.
Any clever ideas?
Use API hooking. Hooking NtCreateFile and a few other calls in ntdll should be enough. I've had good experience using easyhook as a framework to do the hooking itself - free and open source. Even supports managed hooking (c# etc) if you wanted to do that. It's quite easy to set up.
It's at located at http://easyhook.codeplex.com
Edit: btw detours does not allow 64 bit hooking (unless you buy a license for a nominal price of 10,000USD)
EasyHook does not allow native hooks across a WOW64 boundary. It allows managed hooking across WOW64 boundaries though.
I used Microsoft's Detours in the past to track memory allocations by intercepting particular API calls. You could use it to track CreateFile and CreateProcess.
It seems like Dr. Memory's System Call Tracer for Windows is exactly what I was looking for. It is basically a strace implementation for Windows.

Resources