我的客户有两台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()是一个内置的.net函数,可以使用winforms,所以我在我的自定义BringToTheFront()函数中调用它。
显示的最后一个函数Activate()覆盖/隐藏winforms中的内置.net Activate()函数。你可以看到DllImport的东西。
最初,在我的Win7盒子上,我不需要使用p /调用win32调用来实现这一点。我只是打电话给它。激活它并且工作正常。
在Win8.1上,如果我的应用程序仅被最小化,当条形码扫描发生时,它会弹出并获得焦点。但如果它是其他任何东西(未最小化),当扫描发生时,它的图标会在底部闪烁,但它不会出现在前面。
注意已注释掉的this.TopMost = true
。当我取消注释该代码时,应用程序始终保持在前面,并且不允许任何内容在其前面。这种方法具有破坏性,客户不喜欢它。
注意我的线程在睡觉。这些只是实验,希望稍有延迟会有所帮助。它似乎没有。
我能做些什么让这项工作成功吗?
主持人:这不是Bring .NET winform to front (focus) on Windows 8的重复 - 我已经尝试了那里发布的所有内容,但它在Win8上不起作用。所以这澄清了问题并说明了我的尝试。
答案 0 :(得分:2)
您是否尝试过再次打开和关闭TopMost?根据{{3}},该属性不仅仅是设置基础值。