确保 WPF 窗口始终置顶,即使用户点击其他最大化的应用程序

3
我正在尝试确保我的WPF窗口在打开时保持在最前面。它作为一个设置了TopMost=true的弹出窗口,调用了win32 SetWindowPos到TOPMOST。当首次打开时,它会出现在桌面上运行的其他应用程序之上 - 无论是最大化还是非最大化。
如果用户激活或使用应用程序中的窗口,则我的窗口失去焦点并消失。
我想过操作其他应用程序窗口,将其设置为较低的z索引。如何找到应用程序窗口?如何遍历所有窗口?(即使这不是正确的方法,这个问题仍然存在)。
我将使用SetWindowPos、GetForegroundWindow、GetForegroundWindow、GetDesktopWindow等方法。
我怀疑只要用户单击其应用程序,它仍然会聚焦它,因此我正在走错路线。
目前,我的应用程序是一个黑盒子,我无法以另一种方式处理它,例如定期向我的应用程序发送消息以进行聚焦。
我还考虑过拥有一个长时间运行的后台线程,定期聚焦我的WPF弹出窗口,但需要监控资源和处理器。
此致敬礼。

你是说你将窗口的 TopMost=true,但它并不总是保持在最上层? - Gabe
1
这对我来说还可以——当我点击最大化的应用程序时,窗口仍然保持在顶部(尽管它当然仍然失去焦点)。你能发布可重现的代码吗? - itowlson
1个回答

0
尝试这种方法:

public partial class Window1 : System.Windows.Window
{
    private System.Windows.Forms.NotifyIcon trayNotifyIcon;
    private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
    private System.Windows.Forms.ToolStripMenuItem exitMenu;
    private bool isAppExiting = false;
public Window1() { InitializeComponent();
this.Topmost = true; // 创建 NotifyIcon 类的实例 trayNotifyIcon = new System.Windows.Forms.NotifyIcon();
// 此图标文件需要在应用程序的 bin 文件夹中 trayNotifyIcon.Icon = Properties.Resources.MagicRoler_Application;
// 显示托盘通知图标 trayNotifyIcon.Visible = true; trayNotifyIcon.DoubleClick += new EventHandler(trayNotifyIcon_DoubleClick);
// 为上下文菜单创建对象 contextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
// 将菜单项添加到上下文菜单中 System.Windows.Forms.ToolStripMenuItem mnuExit = new System.Windows.Forms.ToolStripMenuItem(); mnuExit.Text = "退出"; mnuExit.Click += new EventHandler(mnuExit_Click); contextMenuStrip.Items.Add(mnuExit);
// 将上下文菜单添加到 Notify Icon 对象中 trayNotifyIcon.ContextMenuStrip = contextMenuStrip; }
void mnuExit_Click(object sender, EventArgs e) { isAppExiting = true; this.Close(); trayNotifyIcon.Visible = false; }
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // 当应用程序关闭时,检查应用程序是从菜单还是窗体关闭按钮退出 if (!isAppExiting) { // 如果触发了窗体关闭按钮,则取消事件并隐藏窗体 // 然后显示通知气球提示 e.Cancel = true; this.Hide(); trayNotifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; trayNotifyIcon.BalloonTipTitle = "应用程序"; trayNotifyIcon.BalloonTipText = "应用程序可以通过系统托盘访问"; trayNotifyIcon.ShowBalloonTip(400); } }
private void Window_StateChanged(object sender, EventArgs e) { switch (this.WindowState) { case WindowState.Maximized: this.Visibility = Visibility.Visible; break; case WindowState.Normal: this.Visibility = Visibility.Visible; break; case WindowState.Minimized: this.WindowState = WindowState.Normal; this.Visibility = Visibility.Hidden; break; } }
void trayNotifyIcon_DoubleClick(object sender, EventArgs e) { switch (this.Visibility) { case Visibility.Collapsed: case Visibility.Hidden: this.Visibility = Visibility.Visible; break; case Visibility.Visible: this.Visibility = Visibility.Hidden; break; } } }

请参考框架的 System.Windows.Forms 组件 (Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll)。 - RockWorld

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接