【发布时间】:2015-02-13 21:46:09
【问题描述】:
我的客户在他们的企业中有两台 Windows 8.1 电脑并排放置。我的 .NET 4.5 winforms 应用程序在两个系统上都运行。如果当用户打开其他程序或单击其他打开的程序时应用程序进入后台,那很好。但是,当发生条形码扫描时,我的 winforms 应用程序应该会出现在所有其他打开的程序之前并位于前台。
它在 Windows 7 上完美运行,但在 Windows 8.1 上不能跳到前面。以下是相关代码:
private void BringToTheFront() {
System.Threading.Thread.Sleep(400);
if (this.WindowState == FormWindowState.Minimized) {
this.WindowState = FormWindowState.Normal;
}
//this.TopMost = true;
this.Activate();
System.Threading.Thread.Sleep(100);
BringToFront();
}
private static class User32 {
[DllImport("User32.dll")]
internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
internal static readonly IntPtr InvalidHandleValue = IntPtr.Zero;
}
public void Activate() {
Process currentProcess = Process.GetCurrentProcess();
IntPtr hWnd = currentProcess.MainWindowHandle;
if (hWnd != User32.InvalidHandleValue) {
User32.SetForegroundWindow(hWnd);
User32.ShowWindow(hWnd, 1);
}
}
关于此代码的几点说明:BringToFront() 是一个可用于 winforms 的内置 .net 函数,因此我在自定义的 BringToTheFront() 函数中调用它。
显示的最后一个函数 Activate() 覆盖/隐藏了 winforms 中的内置 .net Activate() 函数。你可以看到 DllImport 的东西。
最初,在我的 Win7 机器上,我不需要诉诸 p/invoking win32 调用来使其工作。我只是调用了 this.Activate,它运行良好。
在 Win8.1 上,如果我的应用程序只是最小化,当发生条形码扫描时,它会弹出并获得焦点。但如果它在其他任何东西的后面(未最小化),它的图标会在扫描发生时在底部闪烁,但它不会出现在前面。
注意注释掉的this.TopMost = true。当我取消注释该代码时,该应用程序始终位于最前面,并且不允许任何内容出现在其前面。这种方法具有破坏性,客户不喜欢它。
注意我的线程休眠了。这些只是实验,希望稍有延迟会有所帮助。好像没有。
我能做些什么来完成这项工作吗?
主持人:这不是Bring .NET winform to front (focus) on Windows 8 的复制品——我已经尝试了那里发布的所有内容,但它在 Win8 上不起作用。因此,这澄清了问题并说明了我的尝试。
【问题讨论】: