C#
--
Questions
--
Followers
Top Experts
ex)
SendKey("Untitled - Notepad", Keys.A);
#region Function Imports
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
#endregion
#region Constants
// Messages
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
const int WM_CHAR = 0x105;
const int WM_SYSKEYDOWN = 0x104;
const int WM_SYSKEYUP = 0x105;
#endregion
public static void SendKey(string wName, Keys key)
{
IntPtr hWnd = FindWindow(null, wName);
SendMessage(hWnd, WM_KEYDOWN, Convert.ToInt32(key), 0);
SendMessage(hWnd, WM_KEYUP, Convert.ToInt32(key), 0);
}
public static void SendSysKey(string wName, Keys key)
{
IntPtr hWnd = FindWindow(null, wName);
SendMessage(hWnd, WM_SYSKEYDOWN, Convert.ToInt32(key), 0);
SendMessage(hWnd, WM_SYSKEYUP, Convert.ToInt32(key), 0);
}
public static void SendChar(string wName, char c)
{
IntPtr hWnd = FindWindow(null, wName);
SendMessage(hWnd, WM_CHAR, (int)c, 0);
}
Zero AI Policy
We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.
To use SendMessage() you have to retrieve the window handle hWnd of the application you want to talk to.
In fact I would try the following:
Use FindWindow() or FindWindowEx() API to retrieve the hWnd,
then, before any usage of SendKey() you set the focus to the app, using SendMessage()
Const WM_SETFOCUS As Long = &H7
dim hWnd as Long
hWnd = FindWindow("", "your window title")
If hWnd then SendMessage hWnd, WM_SETFOCUS, 0, 0
      IntPtr hwnd = InputSender.FindWindow(nul
      addText("Handle: " + hwnd.ToString());
      StringBuilder title = new StringBuilder(256);
      InputSender.GetWindowText(
      addText(title.ToString());
Outputs:
Handle: 4327520
Untitled - Notepad
...
WM_SETFOCUS (0x7) doesn't seem to be working either...






EARN REWARDS FOR ASKING, ANSWERING, AND MORE.
Earn free swag for participating on the platform.
http://msdn.microsoft.com/en-us/library/ms171548(VS.80).aspx
If I wanted to send a combination (such as Shift+A or Alt+F4) how does that work. I thought all I had to do for alt+f4 was PostMessage(editWnd, 0x104, (int)Keys.F4, 0) but this didn't exit Notepad. Doing a keydown shift and then keydown A didn't make it a shift+A either :(

Get a FREE t-shirt when you ask your first question.
We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.
don't keyup the first key in the sequence until you keydown all you wish to be pressed
C#
--
Questions
--
Followers
Top Experts
C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).