C#给其他程序发消息

1、相关声明函数,SendMessage可定义两种格式。


[DllImport("User32.DLL", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

 

[DllImport("User32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

 

[DllImport("User32.DLL")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);
[DllImport("User32.DLL")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);

 

[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hwnd, int wMsg, IntPtr wParam, string lParam);

 


2、相关消息

public const uint WM_SETTEXT = 0x000C;


public const uint WM_CHAR = 0x0102;


public const uint EM_SETSEL = 0x00B1;

 


3、
用spy++观察是哪个窗口处理消息,然后用FindWindow找到窗口句柄
IntPtr main = FindWindow("TFrmMain", null);


自己启动,比如记事本
Process vProcess = Process.Start("notepad.exe");
while (vProcess.MainWindowHandle == IntPtr.Zero) vProcess.Refresh();
注:启动之后可以直接发键值
SendKeys.Send("01234/n");SendKeys.Send("56789/n");


枚举所有进程
Process[] vP2 = Process.GetProcesses();

 

用FindWindowEx找子窗口句柄,一层层找下去。
IntPtr panel1 = FindWindowEx(main, IntPtr.Zero, "TPanel", null);
IntPtr panel2 = FindWindowEx(panel1, IntPtr.Zero, "TPanel", null);

 

如果有多个同类子窗口,FindWindowEx第二个参数,控制从哪个子窗口开始找何开始找。
IntPtr edit1 = FindWindowEx(panel2, (IntPtr)null, "TEdit", null);
IntPtr edit2 = FindWindowEx(panel2, edit1, "TEdit", null);

 

逐个发消息
SendMessage(edit1, WM_CHAR, (uint)Keys.F3, 0);

 

用循环发
string end="hello";
for(int i=0;i<5;i++)
  SendMessage(edit1, WM_CHAR, (uint)end[i], 0);

 

发字符串
SendMessage(vHandle, WM_SETTEXT, IntPtr.Zero, "测试/r/n换行");

 

选中7个文本
SendMessage(vHandle, EM_SETSEL, 0, 7);

C#给其他程序发消息

上一篇:Windows 环境搭建cocos2dx 3.x Eclipse的环境


下一篇:API - .after