C#中使用User32.dll的常见用法示例

User32.dll是C#中常用的DLL,用于各种与用户界面和窗口相关的操作。以下是C#中使用User32.dll的常见用法示例:

1. 窗口操作:User32.dll提供了操作窗口的函数,如创建、关闭、调整大小、移动和隐藏/显示窗口。例如,可以使用`CreateWindowEx`、`ShowWindow`、`MoveWindow`等函数来控制窗口的行为。

2. 消息处理:User32.dll允许您处理发送到窗口的消息。可以使用`SendMessage`、`PostMessage`和`GetMessage`等函数在窗口之间发送和接收消息,处理用户输入并响应特定事件。

3. 输入控制:User32.dll提供了处理键盘和鼠标输入的函数。例如,可以使用`GetAsyncKeyState`、`SetCursorPos`、`GetCursorPos`等函数来检测按键、设置光标位置和获取光标信息。

4. 剪贴板操作:User32.dll使您能够处理剪贴板。可以使用`OpenClipboard`、`CloseClipboard`、`GetClipboardData`、`SetClipboardData`等函数来访问和修改剪贴板内容。

5. 窗口枚举:User32.dll允许您枚举系统上所有打开的窗口。可以使用`EnumWindows`、`GetWindowText`、`GetWindowRect`等函数来获取每个窗口的信息,如标题、位置和大小。

这些只是User32.dll提供的许多功能中的一些示例。重要的是参考官方文档以获得User32.dll中可用函数的综合列表和使用详细信息。此外,当使用User32.dll或任何其他非托管代码时,请注意错误处理、内存管理和潜在的安全风险。

//示例

       [DllImport("user32.dll")]
        private static extern bool IsWindowVisible(int hWnd);

        [DllImport("USER32.DLL")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("USER32.DLL")]
        private static extern int GetWindowText(int hwnd, StringBuilder lpString, int cch);

        [DllImport("USER32.DLL")]
        private static extern int GetWindowTextLength(int hWnd);

        [DllImport("USER32.DLL")]
        private static extern int EnumWindows(CallBack x, int y);

        private string targetwindow = "目标窗口Title";
       
        private delegate bool CallBack(int hwnd, int lParam);
       
        public int source;
        private int target = 0;
        private bool RE_CallBack(int hwnd, int lParam)
        {

            if (IsWindowVisible(hwnd))
            {
                int cTxtLen = GetWindowTextLength(hwnd) + 1;
                StringBuilder text = new StringBuilder(cTxtLen);
                GetWindowText(hwnd, text, cTxtLen);
                string cTitle = text.ToString();
                if (cTitle.Contains(targetwindow))
                {
                        target= hwnd;

                }

            }
            return true;
        }

        public void Test(int target)
        {
            EnumWindows(RE_CallBack, 0);
            if (target != 0 )
            {
                    SetForegroundWindow(new IntPtr(target));
                    System.Threading.Thread.Sleep(500);
                    SendKeys.SendWait("" + value + "");

            }
           
        }

        public void SetForeWindow(int target)
        {
            EnumWindows(RE_CallBack, 0);
           SetForegroundWindow(new IntPtr(target));

        }
    }

猜你喜欢

转载自blog.csdn.net/qq_33790894/article/details/131706045
今日推荐