Is there an equivalent to SendInput for WPF? I've looked into AutomationPeer classes but was not successfull.
I simply want to send a Keydown (the Enter Key). Simply raising the event (RaiseEvent) does not work in my scenario.
Here is what I have, which is working. I'd prefer to have a managed code alternative.
private void comboSelectionChanged(object sender, SelectionChangedEventArgs args)
{
((ComboBox)sender).Focus();
// send keydown
INPUT input = new INPUT();
input.type = INPUT_KEYBOARD;
input.union.keyboardInput.wVk = 0x0D;
input.union.keyboardInput.time = 0;
SendInput(1, ref input, Marshal.SizeOf(input));
}
[DllImport("user32.dll", SetLastError = true)]
private static extern int SendInput(int nInputs, ref INPUT mi, int cbSize);
[StructLayout(LayoutKind.Sequential)]
private struct INPUT
{
public int type;
public INPUTUNION union;
};
[StructLayout(LayoutKind.Explicit)]
private struct INPUTUNION
{
[FieldOffset(0)]
public MOUSEINPUT mouseInput;
[FieldOffset(0)]
public KEYBDINPUT keyboardInput;
};
[StructLayout(LayoutKind.Sequential)]
private struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
};
[StructLayout(LayoutKind.Sequential)]
private struct KEYBDINPUT
{
public short wVk;
public short wScan;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
};
private const int INPUT_MOUSE = 0;
private const int INPUT_KEYBOARD = 1;
You can emulate a keystroke like this:
public void SendKey(UIElement sourceElement, Key keyToSend)
{
KeyEventArgs args = new KeyEventArgs(InputManager.Current.PrimaryKeyboardDevice, PresentationSource.FromVisual(sourceElement), 0, keyToSend);
args.RoutedEvent = Keyboard.KeyDownEvent;
InputManager.Current.ProcessInput(args);
}
You could then call it like this:
SendKey(myComboBox, Key.Enter);
I suppose you can put this in a static class somewhere, or even make an extension method out of it. However, I would argue that in most cases there is a more elegant way to accomplish this.
I hope this helps.
Related
I'm trying to acquire keyboard input using GetRawInputData and C#. I don't seem to be able to actually read the RAWINPUTDATA fields, no matter what I use for the definition of the call.
I have tried this:
In response to the WM_INPUT message, I try this...
void ProcessRawInput(Message message)
{
uint dwSize = 0;
uint retval;
User32.RAWINPUT rawInput;
retval = User32.GetRawInputData(message.LParam, User32.RAWINPUT.RID_HEADER, out rawInput, ref dwSize, Marshal.SizeOf<User32.RAWINPUTHEADER>());
if (rawInput.header.dwType == (int)User32.RIM_TYPE.RIM_TYPEKEYBOARD)
{
}
}
It seems to read some data into the header structure, but nothing in the RAWINPUTDATA structure.
I tried something like:
if (rawInput.header.dwType == (int)User32.RIM_TYPE.RIM_TYPEKEYBOARD)
{
// set dwSize = Marshal.SizeOf<User32.RAWINPUT>()
retval = User32.GetRawInputData(message.LParam, User32.RAWINPUT.RID_INPUT, out rawInput, ref dwSize, Marshal.SizeOf<User32.RAWINPUTHEADER>());
}
But the only difference seems to be a huge value returned as retval.
I cannot seem to find a useable example (in C#).
My definitions and structures look like this:
[DllImport("User32.dll", SetLastError = true)]
internal static extern uint GetRawInputData(IntPtr hRawInput, uint uiCommand, out RAWINPUT pData, ref uint pcbSize, int cbSizeHeader);
[StructLayout(LayoutKind.Sequential)]
public struct RAWINPUT
{
public const int RID_INPUT = 0x10000003,
RID_HEADER = 0x10000005;
public RAWINPUTHEADER header;
public RAWINPUTDATA data;
}
[StructLayout(LayoutKind.Sequential)]
public struct RAWINPUTHEADER
{
public int dwType;
public int dwSize;
public IntPtr hDevice;
public IntPtr wParam;
}
[StructLayout(LayoutKind.Explicit)]
public struct RAWINPUTDATA
{
[FieldOffset(0)]
public RAWMOUSE Mouse;
[FieldOffset(0)]
public RAWKEYBOARD Keyboard;
[FieldOffset(0)]
public RAWHID HID;
}
[StructLayout(LayoutKind.Sequential)]
public struct RAWKEYBOARD
{
public ushort MakeCode;
public ushort Flags;
public ushort Reserved;
public ushort VKey;
public uint Message;
public ulong ExtraInformation;
}
I have developed a simple Console application to poll an Xbox Controller using xinput. I would like to use the values obtained from one of the thumbsticks to move the mouse. I am able to get the x and y values from the thumbstick, but when I use those values to SendInput() (using the User32.dll), the mouse does not move and the return value is 0.
According to Microsoft, "If the function returns zero, the input was already blocked by another thread."
How do I find the other thread that is blocking it? It is just a simple Console Application (exe) started by Visual Studio that prints the x and y values to the screen and attempts to move the mouse.
long x = controller.x; // values from the controller
long y = controller.y; // these are checked and do contain numbers
INPUT mouseMoveInput = new INPUT();
mouseMoveInput.type = 0; // mouse
mouseMoveInput.mi.dx = x;
mouseMoveInput.mi.dy = y;
mouseMoveInput.mi.mouseData = 0;
mouseMoveInput.mi.dwFlags = MOUSEEVENTF_MOVE;
var result = SendInput(1, ref mouseMoveInput, Marshal.SizeOf(new INPUT());
// result always returns 0
Am I missing something? Should this work?
Here are declarations:
[StructLayout(LayoutKind.Explicit)]
public struct MOUSEINPUT
{
[FieldOffset(0)]
public long X;
[FieldOffset(8)]
public long Y;
[FieldOffset(16)]
public uint MouseData;
[FieldOffset(20)]
public uint Flags;
[FieldOffset(24)]
public uint Time;
[FieldOffset(28)]
public IntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal struct KEYBOARDINPUT
{
public ushort Vk;
public ushort Scan;
public uint Flags;
public uint Time;
public IntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HARDWAREINPUT
{
public uint Msg;
public ushort ParamL;
public ushort ParamH;
}
[StructLayout(LayoutKind.Explicit)]
public struct INPUT
{
[FieldOffset(0)]
public uint type;
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(4)]
public KEYBOARDINPUT ki;
[FieldOffset(4)]
public HARDWAREINPUT hi;
}
UPDATE: using mouse-event does work, but this function is deprecated. Is there a problem with using it anyway since it works?
There is something odd I'm getting with the struct sizes:
Size of tagINPUT: 40
Size of mouseMoveInput: 40
Size of MOUSEINPUT: 32
Size of uint: 4
But if tagINPUT consists of MOUSEINPUT and uint then shouldn't it's size be 36?
The 2nd parameter of SendInput should be a pointer to an array, not a ref parameter, and especially not a ref directly to the struct.
I would also use explicit layout only for the struct that actually needs it, and let the rest be sequential. It's easier.
This code works for me:
const int INPUT_MOUSE = 0;
const int MOUSEEVENTF_MOVE = 0x0001;
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SendInput(uint numberOfInputs, [MarshalAs(UnmanagedType.LPArray)] INPUT[] inputs, int sizeOfInputStructure);
void Main()
{
INPUT mouseMoveInput = new INPUT();
mouseMoveInput.type = INPUT_MOUSE;
mouseMoveInput.mi.dx = 10;
mouseMoveInput.mi.dy = 10;
mouseMoveInput.mi.mouseData = 0;
mouseMoveInput.mi.dwFlags = MOUSEEVENTF_MOVE;
var result = SendInput(1, new INPUT[] { mouseMoveInput}, Marshal.SizeOf(mouseMoveInput));
if(result == 0) {
throw new Win32Exception();
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct HARDWAREINPUT
{
public uint Msg;
public ushort ParamL;
public ushort ParamH;
}
[StructLayout(LayoutKind.Explicit)]
public struct INPUT
{
[FieldOffset(0)]
public uint type;
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public HARDWAREINPUT hi;
}
I am running a c# application that makes use of the sendinputs method in windows to mimic keystrokes. It works fine when I am remoted into the instance, but as soon as I log out it throws an exception. Can anyone offer any thoughts on why this is happening, and how to avoid it?
UPDATE::
here is some sample code that can reproduce the issue.
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ConsoleApplication6
{
class Program
{
class SendKey
{
[StructLayout(LayoutKind.Sequential)]
private struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public int dwExtraInfo;
};
[StructLayout(LayoutKind.Sequential)]
private struct KEYBDINPUT
{
public short wVk;
public short wScan;
public int dwFlags;
public int time;
public int dwExtraInfo;
};
[StructLayout(LayoutKind.Sequential)]
private struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
};
[StructLayout(LayoutKind.Explicit)]
private struct INPUT
{
[FieldOffset(0)]
public int type;
[FieldOffset(4)]
public MOUSEINPUT no;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public HARDWAREINPUT hi;
};
[DllImport("user32.dll")]
private extern static void SendInput(int nInputs, ref INPUT pInputs, int cbsize);
[DllImport("user32.dll", EntryPoint = "MapVirtualKeyA")]
private extern static int MapVirtualKey(int wCode, int wMapType);
private const int INPUT_KEYBOARD = 1;
private const int KEYEVENTF_KEYDOWN = 0x0;
private const int KEYEVENTF_KEYUP = 0x2;
private const int KEYEVENTF_EXTENDEDKEY = 0x1;
private void Send(Keys key, bool isEXTEND)
{
INPUT inp = new INPUT();
inp.type = INPUT_KEYBOARD;
inp.ki.wVk = (short)key;
inp.ki.wScan = (short)MapVirtualKey(inp.ki.wVk, 0);
inp.ki.dwFlags = ((isEXTEND) ? (KEYEVENTF_EXTENDEDKEY) : 0x0) | KEYEVENTF_KEYDOWN;
inp.ki.time = 0;
inp.ki.dwExtraInfo = 0;
SendInput(1, ref inp, Marshal.SizeOf(inp));
System.Threading.Thread.Sleep(100);
inp.ki.dwFlags = ((isEXTEND) ? (KEYEVENTF_EXTENDEDKEY) : 0x0) | KEYEVENTF_KEYUP;
SendInput(1, ref inp, Marshal.SizeOf(inp));
}
static void Main()
{
while(true)
{
System.Threading.Thread.Sleep(2000);
SendKey s = new SendKey();
s.Send(Keys.Z, false);
s.Send(Keys.Left, true);
}
}
}
}
}
if you build this and just run it on a free windows server ec2 instance with notepad in focus it will print zzzzzz continuously while you are remoted into the instance, however, as soon as you remote out of the instance, it will stop printing until you log back in.
i'm new and i need your help resolving this issue.
I'm trying to create a simple debugger to understand how debuggers works and how is loaded exes in memory. I have already written the code which works as well, but now there is the problem: when i try to call WaitForDebugEvent (a kernel32 function) to get the debug event it works, in fact the debug_event variable is written, but this function clears all the variables in my application. So it clear also:
this (current form)
EventArgs (arguments of my form load function)
object sender (the object who called the function)
So i can't continue executing my app because all the vars were deleted. I wouldn't think this is a kernel32 or a Visual Studio bug...
This is the code:
(Structs and imports got from pInvoke.net and MSDN)
[DllImport("kernel32.dll")]
static extern bool DebugActiveProcess(uint dwProcessId);
[DllImport("kernel32.dll", EntryPoint = "WaitForDebugEvent")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitForDebugEvent([In] ref DEBUG_EVENT lpDebugEvent, uint dwMilliseconds);
[DllImport("kernel32.dll")]
static extern bool ContinueDebugEvent(uint dwProcessId, uint dwThreadId, uint dwContinueStatus);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DebugActiveProcessStop([In] int Pid);
public struct DEBUG_EVENT
{
public int dwDebugEventCode;
public int dwProcessId;
public int dwThreadId;
public struct u
{
public EXCEPTION_DEBUG_INFO Exception;
public CREATE_THREAD_DEBUG_INFO CreateThread;
public CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
public EXIT_THREAD_DEBUG_INFO ExitThread;
public EXIT_PROCESS_DEBUG_INFO ExitProcess;
public LOAD_DLL_DEBUG_INFO LoadDll;
public UNLOAD_DLL_DEBUG_INFO UnloadDll;
public OUTPUT_DEBUG_STRING_INFO DebugString;
public RIP_INFO RipInfo;
};
};
[StructLayout(LayoutKind.Sequential)]
public struct EXCEPTION_DEBUG_INFO
{
public EXCEPTION_RECORD ExceptionRecord;
public uint dwFirstChance;
}
[StructLayout(LayoutKind.Sequential)]
public struct EXCEPTION_RECORD
{
public uint ExceptionCode;
public uint ExceptionFlags;
public IntPtr ExceptionRecord;
public IntPtr ExceptionAddress;
public uint NumberParameters;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 15, ArraySubType = UnmanagedType.U4)]
public uint[] ExceptionInformation;
}
public delegate uint PTHREAD_START_ROUTINE(IntPtr lpThreadParameter);
[StructLayout(LayoutKind.Sequential)]
public struct CREATE_THREAD_DEBUG_INFO
{
public IntPtr hThread;
public IntPtr lpThreadLocalBase;
public PTHREAD_START_ROUTINE lpStartAddress;
}
//public delegate uint PTHREAD_START_ROUTINE(IntPtr lpThreadParameter);
[StructLayout(LayoutKind.Sequential)]
public struct CREATE_PROCESS_DEBUG_INFO
{
public IntPtr hFile;
public IntPtr hProcess;
public IntPtr hThread;
public IntPtr lpBaseOfImage;
public uint dwDebugInfoFileOffset;
public uint nDebugInfoSize;
public IntPtr lpThreadLocalBase;
public PTHREAD_START_ROUTINE lpStartAddress;
public IntPtr lpImageName;
public ushort fUnicode;
}
[StructLayout(LayoutKind.Sequential)]
public struct EXIT_THREAD_DEBUG_INFO
{
public uint dwExitCode;
}
[StructLayout(LayoutKind.Sequential)]
public struct EXIT_PROCESS_DEBUG_INFO
{
public uint dwExitCode;
}
[StructLayout(LayoutKind.Sequential)]
public struct LOAD_DLL_DEBUG_INFO
{
public IntPtr hFile;
public IntPtr lpBaseOfDll;
public uint dwDebugInfoFileOffset;
public uint nDebugInfoSize;
public IntPtr lpImageName;
public ushort fUnicode;
}
[StructLayout(LayoutKind.Sequential)]
public struct UNLOAD_DLL_DEBUG_INFO
{
public IntPtr lpBaseOfDll;
}
[StructLayout(LayoutKind.Sequential)]
public struct OUTPUT_DEBUG_STRING_INFO
{
[MarshalAs(UnmanagedType.LPStr)]
public string lpDebugStringData;
public ushort fUnicode;
public ushort nDebugStringLength;
}
[StructLayout(LayoutKind.Sequential)]
public struct RIP_INFO
{
public uint dwError;
public uint dwType;
}
And the main loop of debugger:
private void Form1_Load(object sender, EventArgs e)
{
DebugActiveProcess((uint)Process.GetProcessesByName("notepad")[0].Id);
DEBUG_EVENT debug_event = new DEBUG_EVENT();
CONTEXT context = new CONTEXT();
context.ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL;
while (true)
{
unchecked
{
if (WaitForDebugEvent(ref debug_event, (uint)double.PositiveInfinity))
{
...
ContinueDebugEvent((uint)debug_event.dwProcessId, (uint)debug_event.dwThreadId, (uint)0x10002);
}
}
}
}
What can i do? Thanks in advance...
EDIT:
I have rewritten the code in C++ to see if the problem there was there too. But there was no issue... so i think the problem lays only in C#. This is the code in C++:
IMPORTS:
#include <windows.h>
#include <tlhelp32.h>
#include <msclr\marshal_cppstd.h>
CODE:
private: System::Void DebuggerForm_Load(System::Object^ sender, System::EventArgs^ e) {
std::wstring processName = msclr::interop::marshal_as<std::wstring, String^>("myExe.exe");
DWORD id = getProcessId(processName);
if (id == 0) std::exit(0);
DebugActiveProcess(id);
DEBUG_EVENT debug_event = { 0 };
while (true)
{
if (WaitForDebugEvent(&debug_event, INFINITE)) {
// TODO
ContinueDebugEvent(debug_event.dwProcessId, debug_event.dwThreadId, DBG_CONTINUE);
}
}
}
DWORD getProcessId(const std::wstring& processName)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE)
return 0;
Process32First(processesSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processesSnapshot, &processInfo))
{
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
First of all, You should enable the SE_DEBUG_NAME privilege on the targeted process:
(SE_DEBUG_NAME = "SeDebugPrivilege")
Use OpenProcessToken with TOKEN_ADJUST_PRIVILEGES and TOKEN_QUERY access flags.
Use LookupPrivilegeValue to retrieve the LUID of the SE_DEBUG_NAME privilege name.
Use AdjustTokenPrivileges to enable the SE_DEBUG_NAME privilege.
CloseHandle
For the 3rd step you need a TOKEN_PRIVILEGES structure, where the PrivilegesCount field must set to 1. Also You must set the first(zero index) item of the Privilege field (Luid: see 2nd step, Attributes: SE_PRIVILEGE_ENABLED)
The DEBUG_EVENT structure:
The u field of the structure is an union, it means that it only contains one of the listed structs. Try to use LayoutKind.Explicit and decorate every field with the attribute FieldOffset to define the correct offset inside the structure. Try this:
[StructLayout(LayoutKind.Explicit)]
public struct DEBUG_EVENT
{
[FieldOffset(0)]
public int dwDebugEventCode;
[FieldOffset(4)]
public int dwProcessId;
[FieldOffset(8)]
public int dwThreadId;
[FieldOffset(12)]
[StructLayout(LayoutKind.Explicit)]
public struct u {
[FieldOffset(0)]
public EXCEPTION_DEBUG_INFO Exception;
[FieldOffset(0)]
public CREATE_THREAD_DEBUG_INFO CreateThread;
[FieldOffset(0)]
public CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
[FieldOffset(0)]
public EXIT_THREAD_DEBUG_INFO ExitThread;
[FieldOffset(0)]
public EXIT_PROCESS_DEBUG_INFO ExitProcess;
[FieldOffset(0)]
public LOAD_DLL_DEBUG_INFO LoadDll;
[FieldOffset(0)]
public UNLOAD_DLL_DEBUG_INFO UnloadDll;
[FieldOffset(0)]
public OUTPUT_DEBUG_STRING_INFO DebugString;
[FieldOffset(0)]
public RIP_INFO RipInfo;
}
};
I'm using a Winform to give Buttons in a DirectX Game. Therefore I'm using this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace DirectInput
{
public class cDirectInput
{
[DllImport("user32.dll")]
static extern UInt32 SendInput(UInt32 nInputs, [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] INPUT[] pInputs, Int32 cbSize);
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
public short wVk;
public short wScan;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
}
[StructLayout(LayoutKind.Explicit)]
struct INPUT
{
[FieldOffset(0)]
public int type;
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public HARDWAREINPUT hi;
}
const int KEYEVENTF_EXTENDEDKEY = 0x0001;
const int KEYEVENTF_KEYUP = 0x0002;
const int KEYEVENTF_UNICODE = 0x0004;
const int KEYEVENTF_SCANCODE = 0x0008;
public void Send_Key(short Keycode, int KeyUporDown)
{
INPUT[] InputData = new INPUT[1];
InputData[0].type = 1;
InputData[0].ki.wScan = Keycode;
InputData[0].ki.dwFlags = KeyUporDown;
InputData[0].ki.time = 0;
InputData[0].ki.dwExtraInfo = IntPtr.Zero;
SendInput(1, InputData, Marshal.SizeOf(typeof(INPUT)));
}
}
}
Then I'm sending Buttons with this:
DirectInput.cDirectInput d = new DirectInput.cDirectInput();
d.Send_Key(0x11, 0x0008);
But when I send it it is permanent. When I send w the player is moving forward forever. I can stop that by pressing w on the keyboard. Why isn't it stopping? When I send it to an editor it stops when I stop sending, ingame it doesn't stop. What is the problem?
Thank you in advance!
You're sending a key down message, but not sending a key up message following it. From the documentation:
KEYBDINPUT.dwFlags:
KEYEVENTF_KEYUP (0x0002)
If specified, the key is being released. If not specified, the key is being pressed.
To move forward for 1 second, try:
d.Send_Key(0x11, 0x0008);
Thread.Sleep(1000);
d.Send_Key(0x11, 0x000A);
Note that the reason pressing w fixes the problem is it sends a keydown event (which would be ignored) and then a keyup event, finally releasing the key.