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

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

<完>

相关推荐
董先生_ad986ad2 小时前
C# 中的 `lock` 关键字本质
开发语言·c#
元亓亓亓2 小时前
Java后端开发day36--源码解析:HashMap
java·开发语言·数据结构
道剑剑非道2 小时前
QT 打包安装程序【windeployqt.exe】报错c000007d原因:Conda巨坑
开发语言·qt·conda
小邓儿◑.◑3 小时前
C++武功秘籍 | 入门知识点
开发语言·c++
码银5 小时前
Java 集合:泛型、Set 集合及其实现类详解
java·开发语言
大G哥5 小时前
PHP标签+注释+html混写+变量
android·开发语言·前端·html·php
傻啦嘿哟5 小时前
HTTP代理基础:网络新手的入门指南
开发语言·php
fish_study_csdn5 小时前
pytest 技术总结
开发语言·python·pytest
杨筱毅6 小时前
【优秀三方库研读】【C++基础知识】odygrd/quill -- 折叠表达式
c++·三方库研读
曹牧6 小时前
Java 调用webservice接口输出xml自动转义
java·开发语言·javascript