Win32编程
10、窗口操作
1、课程目标
- 掌握窗口查找和枚举
- 学会窗口消息发送
- 理解窗口属性操作
- 掌握窗口控制技术
2、名词解释
| 术语 | 英文 | 说明 |
|---|---|---|
| 句柄 | HWND | 窗口的唯一标识 |
| 类名 | Class Name | 窗口类的名称 |
| 标题 | Window Title | 窗口的标题文本 |
3、代码实现
3.1、示例1:查找窗口
#include <windows.h>
#include <stdio.h>
void FindWindowDemo() {
// 按类名和标题查找
HWND hWnd = FindWindow(TEXT("Notepad"), NULL);
if (hWnd) {
printf("Found Notepad: %p\n", hWnd);
}
// 仅按标题查找
hWnd = FindWindow(NULL, TEXT("Calculator"));
// 查找子窗口
HWND hEdit = FindWindowEx(hWnd, NULL, TEXT("Edit"), NULL);
}
3.2、示例2:枚举窗口
#include <windows.h>
#include <stdio.h>
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
TCHAR title[256];
TCHAR className[256];
GetWindowText(hWnd, title, 256);
GetClassName(hWnd, className, 256);
if (lstrlen(title) > 0) {
printf("HWND: %p, Class: %ls, Title: %ls\n",
hWnd, className, title);
}
return TRUE; // 继续枚举
}
void EnumerateAllWindows() {
EnumWindows(EnumWindowsProc, 0);
}
// 枚举子窗口
void EnumerateChildWindows(HWND hParent) {
EnumChildWindows(hParent, EnumWindowsProc, 0);
}
3.3、示例3:窗口控制
#include <windows.h>
void WindowControl(HWND hWnd) {
// 显示/隐藏
ShowWindow(hWnd, SW_HIDE);
ShowWindow(hWnd, SW_SHOW);
// 最大化/最小化
ShowWindow(hWnd, SW_MAXIMIZE);
ShowWindow(hWnd, SW_MINIMIZE);
// 移动和调整大小
SetWindowPos(hWnd, NULL, 100, 100, 800, 600, SWP_NOZORDER);
// 置顶
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE);
// 设置标题
SetWindowText(hWnd, TEXT("New Title"));
// 关闭窗口
SendMessage(hWnd, WM_CLOSE, 0, 0);
}
3.4、示例4:模拟输入
#include <windows.h>
#include <stdio.h>
void SimulateInput(HWND hWnd) {
// 发送按键
SendMessage(hWnd, WM_KEYDOWN, VK_RETURN, 0);
SendMessage(hWnd, WM_KEYUP, VK_RETURN, 0);
// 发送文本到Edit控件
HWND hEdit = FindWindowEx(hWnd, NULL, TEXT("Edit"), NULL);
if (hEdit) {
SendMessage(hEdit, WM_SETTEXT, 0, (LPARAM)TEXT("Hello"));
}
// 点击按钮
HWND hButton = FindWindowEx(hWnd, NULL, TEXT("Button"), NULL);
if (hButton) {
SendMessage(hButton, BM_CLICK, 0, 0);
}
}
3.5、示例5:窗口属性
#include <windows.h>
#include <stdio.h>
void WindowProperties(HWND hWnd) {
// 获取窗口样式
LONG style = GetWindowLong(hWnd, GWL_STYLE);
// 检查样式
if (style & WS_VISIBLE) printf("Window is visible\n");
if (style & WS_DISABLED) printf("Window is disabled\n");
// 修改样式(移除边框)
SetWindowLong(hWnd, GWL_STYLE, style & ~WS_CAPTION);
SetWindowPos(hWnd, NULL, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
// 获取窗口矩形
RECT rect;
GetWindowRect(hWnd, &rect);
printf("Position: (%d, %d) - (%d, %d)\n",
rect.left, rect.top, rect.right, rect.bottom);
}
4、课后作业
- 基础练习:实现窗口查找和信息显示工具
- 窗口控制:批量隐藏/显示指定窗口
- 自动化:实现简单的窗口自动化脚本
- 安全应用:检测并获取特定窗口的信息