在 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;
}

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

<完>

相关推荐
wangjinjin18023 分钟前
Python Excel 文件处理:openpyxl 与 pandas 库完全指南
开发语言·python
愚润求学23 分钟前
【C++】类型转换
开发语言·c++
@我漫长的孤独流浪31 分钟前
数据结构测试模拟题(4)
数据结构·c++·算法
斯奕sky_small-BAD35 分钟前
C++ if语句完全指南:从基础到工程实践
java·开发语言·php
Humbunklung1 小时前
Rust Floem UI 框架使用简介
开发语言·ui·rust
csdnzzt1 小时前
从内存角度透视现代C++关键特性
c++
jie188945758661 小时前
C++ 中的 const 知识点详解,c++和c语言区别
java·c语言·c++
网安INF1 小时前
RSA加密算法:非对称密码学的基石
java·开发语言·密码学
明月*清风1 小时前
c++ —— 内存管理
开发语言·c++
蔡蓝1 小时前
设计模式-观察着模式
java·开发语言·设计模式