[C#] 纯文本查看 复制代码#region Win32 API 方法
#region SendMessage 重载
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, StringBuilder lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wparam, IntPtr lparam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);
#endregion
private const uint WM_GETTEXTLENGTH = 0x000E;
private const uint WM_GETTEXT = 0x000D;
private const uint EM_GETSEL = 0xB0;
[DllImport("user32.dll", ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", ExactSpelling = true)]
private static extern IntPtr GetFocus();
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowThreadProcessId(int handle, out int processId);
[DllImport("user32", SetLastError = true, ExactSpelling = true)]
private static extern int AttachThreadInput(int idAttach, int idAttachTo, bool fAttach);
[DllImport("kernel32.dll")]
private static extern int GetCurrentThreadId();
#endregion
private string GetTextFromWin32Api()
{
//获取活动窗口的控件hWnd
int activeWinPtr = GetForegroundWindow().ToInt32();
int activeThreadId = 0;
int processId;
activeThreadId = GetWindowThreadProcessId(activeWinPtr, out processId);
int currentThreadId = GetCurrentThreadId();
if (activeThreadId != currentThreadId)
AttachThreadInput(activeThreadId, currentThreadId, true);
IntPtr activeCtrlId = GetFocus();
//获取全部文本长度
int textlength = (int)SendMessage(activeCtrlId, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero) + 1;
//Have any text at all?
if (textlength > 0)
{
//Get selection
int selstart;
int selend;
SendMessage(activeCtrlId, EM_GETSEL, out selstart, out selend);
StringBuilder sb = new StringBuilder(textlength);
SendMessage(activeCtrlId, WM_GETTEXT, (IntPtr)textlength, sb);
//Slice out selection
string value = sb.ToString();
sb.Clear();
if ((value.Length > 0) && (selend - selstart > 0) && (selstart < value.Length) && (selend < value.Length))
return value.Substring(selstart, selend - selstart);
}
//失败返回null
return null;
}