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

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

<完>

相关推荐
csbysj202043 分钟前
如何使用 XML Schema
开发语言
R6bandito_1 小时前
STM32中printf的重定向详解
开发语言·经验分享·stm32·单片机·嵌入式硬件·mcu
逆小舟1 小时前
【C/C++】指针
c语言·c++·笔记·学习
earthzhang20211 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
江公望1 小时前
Qt QtConcurrent使用入门浅解
c++·qt·qml
杨枝甘露小码1 小时前
Python学习之基础篇
开发语言·python
我是华为OD~HR~栗栗呀1 小时前
23届考研-Java面经(华为OD)
java·c++·python·华为od·华为·面试
武文斌772 小时前
项目学习总结:LVGL图形参数动态变化、开发板的GDB调试、sqlite3移植、MQTT协议、心跳包
linux·开发语言·网络·arm开发·数据库·嵌入式硬件·学习
爱吃喵的鲤鱼2 小时前
仿mudou——Connection模块(连接管理)
linux·运维·服务器·开发语言·网络·c++
爱吃小胖橘2 小时前
Unity网络开发--超文本传输协议Http(1)
开发语言·网络·网络协议·http·c#·游戏引擎