在 VC++ 里最大化并且前置窗口

在 VC++ 里最大化并且前置窗口

在 Windows 系统中,如果需要通过编程的方式,前置显示另一个进程的某个窗口,你会发现,你遇到了一个麻烦。至少你会发现,仅仅使用 SetForegroundWindowSetWindowPos 是没有效果的。

下面是解决方案,在 VC++ 2022VC++ 2019 ,Window 10 和 Windows Server 2019 上测试通过。需要把 C++ 语言版本设置为 C++11 才能编译通过。

注意:缺少的头文件,自己可以根据提示添加上。这里就不写出来了。

cpp 复制代码
BOOL AltDown()
{
  INPUT input;

  memset(&input, 0, sizeof(INPUT));
  input.type = INPUT_KEYBOARD;
  input.ki.wVk = VK_MENU;
  SendInput(1, &input, sizeof(INPUT));
  return TRUE;
}

BOOL AltUp()
{
  INPUT input;

  memset(&input, 0, sizeof(INPUT));
  input.type = INPUT_KEYBOARD;
  input.ki.dwFlags = KEYEVENTF_KEYUP;
  input.ki.wVk = VK_MENU;
  SendInput(1, &input, sizeof(INPUT));
  return TRUE;
}

BOOL 最大化置前显示窗口(HWND hwnd)
{
   HWND h_foreground_window{GetForegroundWindow()};

  if (!h_foreground_window)
    h_foreground_window = FindWindowW(L"Shell_TrayWnd", nullptr);

  if (hwnd == h_foreground_window) {
    ShowWindow(hwnd, SW_MAXIMIZE);
    return TRUE;
  }

  if (IsIconic(hwnd))
    ShowWindow(hwnd, SW_RESTORE);

  ShowWindow(hwnd, SW_MAXIMIZE);

  BOOL res{SetForegroundWindow(hwnd)};
  if (!res) {
    DWORD my_thread{}, current_foreground_thread{}, hwnd_thread{};

    my_thread = GetCurrentThreadId();
    current_foreground_thread
      = GetWindowThreadProcessId(h_foreground_window, nullptr);
    hwnd_thread = GetWindowThreadProcessId(hwnd, nullptr);

    AttachThreadInput(my_thread, hwnd_thread, TRUE);
    AttachThreadInput(my_thread, current_foreground_thread, TRUE);
    AttachThreadInput(current_foreground_thread, hwnd_thread, TRUE);

    res = SetForegroundWindow(hwnd);
    if (!res) {
      AltDown();
      AltUp();
      AltDown();
      AltUp();
      res = SetForegroundWindow(hwnd);
    }
    AttachThreadInput(my_thread, hwnd_thread, FALSE);
    AttachThreadInput(my_thread, current_foreground_thread, FALSE);
    AttachThreadInput(current_foreground_thread, hwnd_thread, FALSE);
  }
  // 之所以设置失败,有可能是因为这个时候有人操作了键盘或鼠标。
  return res;
}

这可能是你找遍全网才能找到的方案。

<完>

相关推荐
十八朵郁金香7 分钟前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript
阿尔法波11 分钟前
python与pycharm如何设置文件夹为源代码根目录
开发语言·python·pycharm
xing251619 分钟前
pytest下allure
开发语言·python·pytest
眸笑丶24 分钟前
使用 Python 调用 Ollama API 并调用 deepseek-r1:8b 模型
开发语言·python
enyp801 小时前
Qt QStackedWidget 总结
开发语言·qt
gu201 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
lly2024061 小时前
SQLite 删除表
开发语言
wjs20241 小时前
HTML 字符实体
开发语言
二十雨辰1 小时前
[Java基础]网络编程
java·开发语言
cookies_s_s1 小时前
Linux--进程(进程虚拟地址空间、页表、进程控制、实现简易shell)
linux·运维·服务器·数据结构·c++·算法·哈希算法