Hi Fapsterx,
This should give you an idea. Your problem is: most times you can not send an input to the main window of an application. Most applications use some kind of child-window for editing (a TextBox, whatever).
So you can only send input messages to those. But how to find them? Thats the difficult part, and I dont know the ultimate answer, you have to find it out for every application (you could use tools like spy++)
My code shows the needed steps with notepad as an example.(the edit controls class is "Edit").
It's a complete example just copy to a new console project, add a reference to WindowsForms (or start with a WindowsForms project). (We need the reference here for using the Clipboard class).
Then start notepad and run the code (caution no error handling present!)
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace SendKeysToAnyApplication
{
class Program
{
delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);
[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
const uint WM_CHAR = 0x102;
const uint WM_PASTE = 0x0302;
static IntPtr m_hWndEdit = IntPtr.Zero;
[STAThread]
static void Main(string[] args)
{
IntPtr hWnd = FindWindow("Notepad", null);
IntPtr hWndEdit = IntPtr.Zero;
EnumChildWindows(hWnd, EnumChildWindowsCallback, hWndEdit);
if (m_hWndEdit != null)
{
Clipboard.SetText("this is magic!");
SendMessage(m_hWndEdit, WM_PASTE, 0, 0);
}
}
static bool EnumChildWindowsCallback(IntPtr hWnd, IntPtr lParam)
{
StringBuilder sb = new StringBuilder();
GetClassName(hWnd, sb, 256);
if (!sb.ToString().Contains("Edit"))
{
return true;
}
m_hWndEdit = hWnd;
return false;
}
}
}