当前位置: 移动技术网 > 网络运营>服务器>Windows > Win32 程序在启动时如何激活前一个启动程序的窗口

Win32 程序在启动时如何激活前一个启动程序的窗口

2019年04月17日  | 移动技术网网络运营  | 我要评论

uwp 程序天生单实例。当然,新 api (10.0.17134)开始也提供了多实例功能。不过,传统 win32 程序可就要自己来控制单实例了。

本文介绍简单的几个 win32 方法调用,使 win32 程序也支持单实例。

激活之前进程的窗口

我们可以通过进程名称找到此前已经启动过的进程实例,如果发现,就激活它的窗口。

[stathread]
static void main(string[] args)
{
  var current = process.getcurrentprocess();
  var process = process.getprocessesbyname(current.processname).firstordefault(x => x.id != current.id);
  if (process != null)
  {
    var hwnd = process.mainwindowhandle;
    showwindow(hwnd, 9);
    return;
  }
  // 启动自己的主窗口,此部分代码省略。
}
[dllimport("user32.dll")]
private static extern int showwindow(intptr hwnd, uint ncmdshow);

你一定觉得那个 9 很奇怪,它是多个不同的 ncmdshow 的值:

hide
minimized
maximized
restore

另外,找到的窗口此时可能并不处于激活状态。例如在 windows 10 中,此窗口可能在其他桌面上。那么我们需要添加额外的代码将其显示出来。

在前面的 showwindow 之后,再调用一下 setforegroundwindow 即可将其激活到最前面来。如果在其他桌面,则会切换到对应的桌面。

[dllimport("user32.dll")]
public static extern bool setforegroundwindow(intptr hwnd);
var hwnd = process.mainwindowhandle;
showwindow(hwnd, 9);
setforegroundwindow(hwnd);

找到并激活窗口

以上方法适用于普通的主窗口。然而当窗口并不是进程的主窗口,或者 showintaskbar 设为了 false 的时候就不生效了(此时窗口句柄会改变)。

于是,我们需要改用其他的方式来查找窗口。

[stathread]
static void main(string[] args)
{
  var hwnd = findwindow(null, "那个窗口的标题栏文字");
  if (hwnd != intptr.zero)
  {
    showwindow(hwnd, 9);
    return;
  }
  // 启动自己的主窗口,此部分代码省略。
}
[dllimport("user32.dll", charset = charset.unicode)]
public static extern intptr findwindow(string lpclassname, string lpwindowname);

总结

以上所述是小编给大家介绍的win32 程序在启动时激活前一个启动程序的窗口,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网