一,windowsAPI助手类
using NLog; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace Gateway { public class WindowAPI { private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam); public struct WindowInfo { public IntPtr hWnd; public string szWindowName; public string szClassName; } public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } private static Logger logger = LogManager.GetCurrentClassLogger(); public static int BM_CLICK = 245; public static int WS_DISABLED = 134217728; public static int WM_CLOSE = 16; public static int WM_COMMAND = 273; public static int WM_GETTEXT = 13; public static int WM_CLICK = 245; public static int WM_SETTEXT = 12; public static int WM_LBUTTONDOWN = 513; public static int WM_LBUTTONUP = 514; public static int LB_GETCOUNT = 395; public static int MOUSEEVENTF_MOVE = 1; public static int MOUSEEVENTF_LEFTDOWN = 2; public static int MOUSEEVENTF_LEFTUP = 4; public static int MOUSEEVENTF_RIGHTDOWN = 8; public static int MOUSEEVENTF_RIGHTUP = 16; public static int MOUSEEVENTF_MIDDLEDOWN = 32; public static int MOUSEEVENTF_MIDDLEUP = 64; public static int MOUSEEVENTF_ABSOLUTE = 32768; public static int MOUSEEVENTF_WHEEL = 2048; public const uint TCM_FIRST = 4864u; public const uint TCM_GETIMAGELIST = 4866u; public const uint TCM_SETIMAGELIST = 4867u; public const uint TCM_GETITEMCOUNT = 4868u; public const uint TCM_GETITEMA = 4869u; public const uint TCM_GETITEMW = 4924u; public const uint TCM_SETITEMA = 4870u; public const uint TCM_SETITEMW = 4925u; public const uint TCM_INSERTITEMA = 4871u; public const uint TCM_INSERTITEMW = 4926u; public const uint TCM_DELETEITEM = 4872u; public const uint TCM_DELETEALLITEMS = 4873u; public const uint TCM_GETITEMRECT = 4874u; public const uint TCM_GETCURSEL = 4875u; public const uint TCM_SETCURSEL = 4876u; public const uint TCM_HITTEST = 4877u; public const uint TCM_SETITEMEXTRA = 4878u; public const uint TCM_ADJUSTRECT = 4904u; public const uint TCM_SETITEMSIZE = 4905u; public const uint TCM_REMOVEIMAGE = 4906u; public const uint TCM_SETPADDING = 4907u; public const uint TCM_GETROWCOUNT = 4908u; public const uint TCM_GETCURFOCUS = 4911u; public const uint TCM_SETCURFOCUS = 4912u; public const uint TCM_SETMINTABWIDTH = 4913u; public const uint TCM_DESELECTALL = 4914u; public const uint TCM_HIGHLIGHTITEM = 4915u; public const uint TCM_SETEXTENDEDSTYLE = 4916u; public static IntPtr HWND_TOPMOST = new IntPtr(-1); private const int SW_HIDE = 0; private const int SW_SHOWNORMAL = 1; private const int SW_SHOWMINIMIZED = 2; private const int SW_SHOWMAXIMIZED = 3; private const int SW_SHOWNOACTIVATE = 4; private const int SW_RESTORE = 9; private const int SW_SHOWDEFAULT = 10; private static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); private static readonly IntPtr HWND_TOP = new IntPtr(0); private const uint SWP_NOSIZE = 1u; private const uint SWP_NOMOVE = 2u; private const uint SWP_NOZORDER = 4u; private const uint SWP_NOREDRAW = 8u; private const uint SWP_NOACTIVATE = 16u; private const uint SWP_FRAMECHANGED = 32u; private const uint SWP_SHOWWINDOW = 64u; private const uint SWP_HIDEWINDOW = 128u; private const uint SWP_NOCOPYBITS = 256u; private const uint SWP_NOOWNERZORDER = 512u; private const uint SWP_NOSENDCHANGING = 1024u; [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hwnd, int wCmd); [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int nMaxCount); [DllImport("user32.dll", ExactSpelling = true)] private static extern bool EnumChildWindows(IntPtr hwndParent, WNDENUMPROC lpEnumFunc, int lParam); [DllImport("user32.dll")] private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam); [DllImport("user32.dll")] private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount); [DllImport("user32.dll")] private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount); [DllImport("user32.dll")] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndlnsertAfter, int X, int Y, int cx, int cy, uint Flags); [DllImport("User32.dll")] public static extern int PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("User32.dll")] public static extern int PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, int lParam); [DllImport("User32.dll")] public static extern int PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern bool EnableWindow(IntPtr hWnd, bool bEnable); [DllImport("user32.dll")] public static extern IntPtr GetMenu(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr GetSubMenu(IntPtr hMenu, int nPos); [DllImport("user32.dll")] public static extern IntPtr GetMenuItemID(IntPtr hMenu, int nPos); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int SetWindowText(IntPtr hwnd, string lpString); [DllImport("User32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam); [DllImport("user32.dll", EntryPoint = "SendMessageA")] public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern void SendMessage(IntPtr hwnd, int wMsg, int wParam, StringBuilder lParam); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, int lParam); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hwnd, int wMsg, string wParam, string lParam); [DllImport("User32.dll")] public static extern int PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam); [DllImport("user32.dll", SetLastError = true)] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect); [DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool IsZoomed(IntPtr hWnd); [DllImport("user32.dll")] private static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId); [DllImport("user32.dll")] private static extern IntPtr AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, int fAttach); public static void WM_LBOption(IntPtr hwnd) { SendMessage(hwnd, WM_LBUTTONDOWN, 0, 0); PostMessage(hwnd, WM_LBUTTONUP, 0, 0); Thread.Sleep(20); } public static void WM_LBOption(IntPtr hwnd, IntPtr wParam, IntPtr lParam) { PostMessage(hwnd, WM_LBUTTONDOWN, wParam, lParam); PostMessage(hwnd, WM_LBUTTONUP, wParam, lParam); Thread.Sleep(20); } public static void WM_LBOptionHandler(IntPtr hwnd, IntPtr wParam, IntPtr lParam, Func<bool> func) { int num = 0; do { WM_LBOption(hwnd, wParam, lParam); Thread.Sleep(2000); if (!func()) { num++; continue; } return; } while (num <= 3); throw new Exception("虚拟操作触发失败"); } [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(Point point); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr GetForegroundWindow(); [DllImport("Kernel32.dll")] public static extern bool SetLocalTime(ref SYSTEMTIME Time); [DllImport("Kernel32.dll")] public static extern void GetLocalTime(ref SYSTEMTIME Time); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern uint SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam); [DllImport("user32.dll")] public static extern int SetCursorPos(int x, int y); [DllImport("user32")] public static extern int mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo); public static List<WindowInfo> GetEnumChildWindowsCallback(IntPtr handle, string name, string classname) { List<WindowInfo> wndList = new List<WindowInfo>(); EnumChildWindows(handle, delegate(IntPtr hWnd, int lParam) { WindowInfo item = default(WindowInfo); StringBuilder stringBuilder = new StringBuilder(256); item.hWnd = hWnd; GetWindowTextW(hWnd, stringBuilder, stringBuilder.Capacity); item.szWindowName = stringBuilder.ToString(); GetClassNameW(hWnd, stringBuilder, stringBuilder.Capacity); item.szClassName = stringBuilder.ToString(); wndList.Add(item); return true; }, 0); IEnumerable<WindowInfo> source = wndList.Where((WindowInfo it) => it.szClassName.ToLower() == classname.ToLower()); if (name != null) { source = source.Where((WindowInfo it) => it.szWindowName.ToLower() == name.ToLower()); } return source.ToList(); } public static WindowInfo GetEnumChildWindowsCallbackP(IntPtr handle, string name, string classname) { List<WindowInfo> wndList = new List<WindowInfo>(); EnumChildWindows(handle, delegate(IntPtr hWnd, int lParam) { WindowInfo item = default(WindowInfo); StringBuilder stringBuilder = new StringBuilder(256); item.hWnd = hWnd; GetWindowTextW(hWnd, stringBuilder, stringBuilder.Capacity); item.szWindowName = stringBuilder.ToString(); GetClassNameW(hWnd, stringBuilder, stringBuilder.Capacity); item.szClassName = stringBuilder.ToString(); wndList.Add(item); return true; }, 0); IEnumerable<WindowInfo> source = wndList.Where((WindowInfo it) => it.szClassName.ToLower() == classname.ToLower()); return source.ToList().FirstOrDefault(); } public static List<WindowInfo> GetEnumChildWindowsCallbackListP(IntPtr handle, string name, string classname) { List<WindowInfo> wndList = new List<WindowInfo>(); EnumChildWindows(handle, delegate(IntPtr hWnd, int lParam) { WindowInfo item = default(WindowInfo); StringBuilder stringBuilder = new StringBuilder(256); item.hWnd = hWnd; GetWindowTextW(hWnd, stringBuilder, stringBuilder.Capacity); item.szWindowName = stringBuilder.ToString(); GetClassNameW(hWnd, stringBuilder, stringBuilder.Capacity); item.szClassName = stringBuilder.ToString(); wndList.Add(item); return true; }, 0); IEnumerable<WindowInfo> source = wndList.Where((WindowInfo it) => it.szClassName.ToLower() == classname.ToLower()); if (name != null) { source = source.Where((WindowInfo it) => it.szWindowName.ToLower() == name.ToLower()); } return source.ToList(); } public static List<WindowInfo> GetEnumChildWindowsCallback(IntPtr handle) { List<WindowInfo> wndList = new List<WindowInfo>(); EnumChildWindows(handle, delegate(IntPtr hWnd, int lParam) { WindowInfo item = default(WindowInfo); StringBuilder stringBuilder = new StringBuilder(256); item.hWnd = hWnd; GetWindowTextW(hWnd, stringBuilder, stringBuilder.Capacity); item.szWindowName = stringBuilder.ToString(); GetClassNameW(hWnd, stringBuilder, stringBuilder.Capacity); item.szClassName = stringBuilder.ToString(); wndList.Add(item); return true; }, 0); return wndList.ToList(); } public static List<WindowInfo> GetAllDesktopWindows(string name, string classname) { List<WindowInfo> wndList = new List<WindowInfo>(); EnumWindows(delegate(IntPtr hWnd, int lParam) { WindowInfo item = default(WindowInfo); StringBuilder stringBuilder = new StringBuilder(256); item.hWnd = hWnd; GetWindowTextW(hWnd, stringBuilder, stringBuilder.Capacity); item.szWindowName = stringBuilder.ToString(); GetClassNameW(hWnd, stringBuilder, stringBuilder.Capacity); item.szClassName = stringBuilder.ToString(); wndList.Add(item); return true; }, 0); if (name != null) { wndList = wndList.Where((WindowInfo it) => it.szWindowName.ToLower() == name.ToLower()).ToList(); } if (classname != null) { wndList = wndList.Where((WindowInfo it) => it.szClassName.ToLower() == classname.ToLower()).ToList(); } return wndList; } public static WindowInfo GetEnumChildWindowsFirst(IntPtr handle, string name, string classname) { return GetEnumChildWindowsCallback(handle, name, classname).FirstOrDefault(); } public static WindowInfo GetAllDesktopWindowsFirst(string name, string classname) { return GetAllDesktopWindows(name, classname).FirstOrDefault(); } public static WindowInfo GetAllDesktopWindowsFirst(Func<WindowInfo, bool> func) { List<WindowInfo> allDesktopWindows = GetAllDesktopWindows(null, null); return allDesktopWindows.FirstOrDefault((WindowInfo a) => func(a)); } public static WindowInfo GetEnumChildWindowsCallbackFirst(IntPtr handle, Func<WindowInfo, bool> func) { List<WindowInfo> enumChildWindowsCallback = GetEnumChildWindowsCallback(handle); return enumChildWindowsCallback.FirstOrDefault((WindowInfo a) => func(a)); } public static string GetTitle(IntPtr handle) { int windowTextLength = GetWindowTextLength(handle); StringBuilder stringBuilder = new StringBuilder(windowTextLength + 1); GetWindowText(handle, stringBuilder, stringBuilder.Capacity); return stringBuilder.ToString(); } public static int[] GetProcessIDByIntPtr(IntPtr hWnd) { int[] array = new int[2]; int ID = 0; int num = 0; num = GetWindowThreadProcessId(hWnd, out ID); array[0] = ID; array[1] = num; return array; } public static void MouseClick(int x, int y) { SetCursorPos(x, y); mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_ABSOLUTE, x, y, 0, IntPtr.Zero); mouse_event(MOUSEEVENTF_LEFTUP | MOUSEEVENTF_ABSOLUTE, x, y, 0, IntPtr.Zero); } public static void MouseDoubleClick(int x, int y) { MouseClick(x, y); MouseClick(x, y); } public static IntPtr MouseIntPtr(int x, int y) { Point point = new Point(x, y); return WindowFromPoint(point); } public static string IntptrString(IntPtr intPtr) { int num = 10000; IntPtr intPtr2; string s; while (true) { s = new string(new char[num]); intPtr2 = Marshal.StringToHGlobalAnsi(s); int num2 = SendMessage(intPtr, WM_GETTEXT, num, intPtr2); if (num2 + 100 <= num) { break; } num *= 2; if (num >= 10000000) { break; } s = null; } string result = Marshal.PtrToStringAnsi(intPtr2); s = null; return result; } public static void MouseClickToText(int x, int y, string text) { SetCursorPos(x, y); mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_ABSOLUTE, x, y, 0, IntPtr.Zero); mouse_event(MOUSEEVENTF_LEFTUP | MOUSEEVENTF_ABSOLUTE, x, y, 0, IntPtr.Zero); Thread.Sleep(300); //SendKeys.SendWait(text); } public static void ExeTop(IntPtr intPtr) { DateTime now = DateTime.Now; ActivateWindow(intPtr); do { if (GetForegroundWindow() != intPtr) { Thread.Sleep(500); logger.DebugEncryption("重新置顶"); MessageCommon.AddMessage("重新置顶"); ActivateWindow(intPtr); continue; } return; } while (!(DateTime.Now.Subtract(now).TotalSeconds > 20.0)); throw new Exception("置顶失败"); } public static void ActivateWindow(IntPtr hWnd) { if (!(hWnd == GetForegroundWindow())) { IntPtr windowThreadProcessId = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero); IntPtr windowThreadProcessId2 = GetWindowThreadProcessId(hWnd, IntPtr.Zero); if (windowThreadProcessId != windowThreadProcessId2) { AttachThreadInput(windowThreadProcessId, windowThreadProcessId2, 1); SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, 3u); SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, 3u); SetForegroundWindow(hWnd); AttachThreadInput(windowThreadProcessId, windowThreadProcessId2, 0); } else { SetForegroundWindow(hWnd); } if (IsIconic(hWnd)) { ShowWindowAsync(hWnd, 9); } else { ShowWindowAsync(hWnd, 1); } } } } }
二,解析
Api函数是构筑Windws应用程序的基石,每一种Windows应用程序开发工具,它提供的底层函数都间接或直接地调用了Windows API函数,同时为了实现功能扩
展,一般也都提供了调用WindowsAPI函数的接口, 也就是说具备调用动态连接库的能力。Visual C#和其它开发工具一样也能够调用动态链接库的API函
数。.NET框架本身提供了这样一种服务,允许受管辖的代码调用动态链接库中实现的非受管辖函数,包括操作系统提供的Windows API函数。它能够定位和调用输
出函数,根据需要,组织其各个参数(整型、字符串类型、数组、和结构等等)跨越互操作边界。
下面以C#为例简单介绍调用API的基本过程:
动态链接库函数的声明
动态链接库函数使用前必须声明,相对于VB,C#函数声明显得更加罗嗦,前者通过 Api Viewer粘贴以后,可以直接使用,而后者则需要对参数作些额外的变化工作。
动态链接库函数声明部分一般由下列两部分组成,一是函数名或索引号,二是动态链接库的文件名。
譬如,你想调用User32.DLL中的MessageBox函数,我们必须指明函数的名字MessageBoxA或MessageBoxW,以及库名字User32.dll,我们知道Win32 API对每一
个涉及字符串和字符的函数一般都存在两个版本,单字节字符的ANSI版本和双字节字符的UNICODE版本。
下面是一个调用API函数的例子:
[DllImport("KERNEL32.DLL", EntryPoint="MoveFileW", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] public static extern bool MoveFile(String src, String dst);
其中入口点EntryPoint标识函数在动态链接库的入口位置,在一个受管辖的工程中,目标函数的原始名字和序号入口点不仅标识一个跨越互操作界限的函数。
而且,你还可以把这个入口点映射为一个不同的名字,也就是对函数进行重命名。重命名可以给调用函数带来种种便利,通过重命名,一方面我们不用为函数
的大小写伤透脑筋,同时它也可以保证与已有的命名规则保持一致,允许带有不同参数类型的函数共存,更重要的是它简化了对ANSI和Unicode版本的调用。
CharSet用于标识函数调用所采用的是Unicode或是ANSI版本,ExactSpelling=false将告诉编译器,让编译器决定使用Unicode或者是Ansi版本。其它的参数请参考MSDN在线帮助.
在C#中,你可以在EntryPoint域通过名字和序号声明一个动态链接库函数,如果在方法定义中使用的函数名与DLL入口点相同,你不需要在EntryPoint域显示
声明函数。否则,你必须使用下列属性格式指示一个名字和序号。
[DllImport("dllname", EntryPoint="Functionname")] [DllImport("dllname", EntryPoint="#123")] 值得注意的是,你必须在数字序号前加“#” 下面是一个用MsgBox替换MessageBox名字的例子: [C#] using System.Runtime.InteropServices; public class Win32 { [DllImport("user32.dll", EntryPoint="MessageBox")] public static extern int MsgBox(int hWnd, String text, String caption, uint type); }
许多受管辖的动态链接库函数期望你能够传递一个复杂的参数类型给函数,譬如一个用户定义的结构类型成员或者受管辖代码定义的一个类成员,这时你必须提
供额外的信息格式化这个类型,以保持参数原有的布局和对齐。
三,以下是一些常见的 Window API 函数:
CreateWindowEx
:创建并显示一个新的窗口。该函数指定窗口的样式、类、标题、位置和大小等信息。ShowWindow
:显示或隐藏窗口。该函数用于将窗口设置为可见或不可见状态。UpdateWindow
:更新窗口。该函数用于强制窗口重新绘制。SetWindowPos
:设置窗口的位置和大小。该函数用于将窗口移动到屏幕上的指定位置,并可以调整窗口的大小。GetWindowRect
:获取窗口的边界矩形。该函数返回一个包含窗口左上角和右下角坐标的矩形。SetWindowRgn
:设置窗口的区域。该函数用于设置窗口的形状和大小,可以创建不规则形状的窗口。GetClientRect
:获取客户区域矩形。该函数返回一个包含窗口客户区域左上角和右下角坐标的矩形。InvalidateRect
:使窗口无效。该函数用于强制窗口重新绘制,通常在窗口大小或位置发生更改时使用。BeginPaint
:开始绘制窗口。该函数用于开始绘制窗口的过程,并返回一个绘制上下文对象。EndPaint
:结束绘制窗口。该函数用于结束绘制窗口的过程。GetDC
:获取设备上下文。该函数用于获取用于绘制的设备上下文对象。ReleaseDC
:释放设备上下文。该函数用于释放用于绘制的设备上下文对象。PostMessage
:发送消息到窗口。该函数用于向指定窗口发送消息,例如点击事件或按键事件等。TranslateMessage
:翻译消息。该函数用于将虚拟键码转换为字符代码,以便可以处理键盘输入事件。DispatchMessage
:分发消息。该函数用于将消息分发给窗口处理程序进行处理。
以上仅是一些常见的 Window API 函数示例,实际上还有很多其他的函数可用于创建和控制窗口。
标签:------------------------,IntPtr,const,C#,hWnd,int,Windows,static,public From: https://www.cnblogs.com/misakayoucn/p/17819340.html