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

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

<完>

相关推荐
wuqingshun31415913 分钟前
蓝桥杯 16. 外卖店优先级
c++·算法·职场和发展·蓝桥杯·深度优先
海绵宝宝贾克斯儿1 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01121 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
Epiphany.5561 小时前
素数筛(欧拉筛算法)
c++·算法·图论
龙湾开发1 小时前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 10.增强表面细节(二)法线贴图
c++·笔记·学习·图形渲染·贴图
whoarethenext1 小时前
c/c++的opencv的轮廓匹配初识
c语言·c++·opencv
爱吃涮毛肚的肥肥(暂时吃不了版)1 小时前
项目班——0510——JSON网络封装
c++·算法·json
isyangli_blog1 小时前
(1-4)Java Object类、Final、注解、设计模式、抽象类、接口、内部类
java·开发语言
apocelipes1 小时前
使用libdivide加速整数除法运算
c语言·c++·性能优化·linux编程
三块钱07941 小时前
【原创】基于视觉大模型gemma-3-4b实现短视频自动识别内容并生成解说文案
开发语言·python·音视频