我尝试将文本消息发送到 Windows 7 中的各种应用程序(例如 Notepad++、Notepad 等)。SendMessage 适用于记事本,但不适用于记事本++。
如果我将文本发送到记事本,一切看起来都很好,整个文本,我得到 1 作为 SendMessage 方法的返回。但是对于 Notepad++,只出现第一个字母并且方法 SendMessage 返回 0,但是 Marshal.GetLastWin32Error() 没有返回任何错误(结果 0)?
这是代码:
GUITHREADINFO gti = new GUITHREADINFO();
IntPtr hWnd = GetForegroundWindow();
uint processId;
uint activeThreadId = GetWindowThreadProcessId(hWnd, out processId);
if (GetInfo(activeThreadId, out gti))
{
int EM_REPLACESEL = 0x00C2;
int error = Marshal.GetLastWin32Error();
int result = SendMessageW(gti.hwndCaret, EM_REPLACESEL, -1, passed);//3rd param doesn't change anything
error = Marshal.GetLastWin32Error();
}
WinAPI 函数和 GetInfo 方法只要具有所需的结构就定义为:
[DllImport("User32.dll", EntryPoint = "SendMessageW", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int SendMessageW(IntPtr hWnd, int uMsg, int wParam, string lParam);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
//"Borrowed" code
public static bool GetInfo(uint hwnd, out GUITHREADINFO lpgui)
{
uint lpdwProcessId;
uint threadId = GetWindowThreadProcessId(hwnd, out lpdwProcessId);
lpgui = new GUITHREADINFO();
lpgui.cbSize = Marshal.SizeOf(lpgui);
return GetGUIThreadInfo(threadId, ref lpgui);
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int iLeft;
public int iTop;
public int iRight;
public int iBottom;
}
[StructLayout(LayoutKind.Sequential)]
public struct GUITHREADINFO
{
public int cbSize;
public int flags;
public IntPtr hwndActive;
public IntPtr hwndFocus;
public IntPtr hwndCapture;
public IntPtr hwndMenuOwner;
public IntPtr hwndMoveSize;
public IntPtr hwndCaret;
public RECT rectCaret;
}
太好了,我想知道我应该怎么做才能修复它,这样它才能(完全)适用于所有窗口,而不仅仅是记事本中的编辑控制?