带有 MB_TOPMOST 的 .NET MessageBox 显示在其他应用程序后面

时间:2021-04-21 14:16:06

标签: c# messagebox

internal class NativeMethods
{
     [DllImport("user32.dll", CharSet = CharSet.Auto)]
     internal static extern int MessageBox(
         IntPtr windowHandle,
         [param: MarshalAs(UnmanagedType.LPWStr)]
         string message,
         [param: MarshalAs(UnmanagedType.LPWStr)]
         string title,
         uint type);
}

messageBoxResult = NativeMethods.MessageBox(
    (IntPtr)0, 
    text, 
    "Title", 
    (int)(NativeMethods.MB_OK | NativeMethods.MB_ICONINFORMATION | NativeMethods.MB_TOPMOST));

我调用 MessageBox 两次,第一个没有显示TOPMOST,第二个确实显示TOPMOST(在我点击第一个之后)。我已经尝试将 windowHandle 设置为 NULL 并添加 MB_SETFOREGROUND 标志。我的应用程序没有单独的窗口。

它总是在第一个 MessageBox 前面的同一个窗口。它是一个与我的应用程序通信的 c# 客户端。如果例如Visual Studio 可见,第一个 MessageBox 按预期工作。我的假设是客户端应用程序以某种方式比我的第一个 MessageBox 具有更高的优先级。显示后是否需要使用 SetForegroundWindow 将 MessageBox 设置为前景?

知道为什么我的第一个 MessageBox 隐藏在应用程序后面而第二个没有吗?

1 个答案:

答案 0 :(得分:0)

我的主要问题是 MessageBox 前面总是有一个特定的应用程序。因此,我的解决方案是获取应用程序的 MainWindowHandle 并将其传递给 MessageBox。

备注:为什么我要检查是否有确切的一个进程?该应用程序只能打开一次,如果超过一个则说明问题更大。

var processes = Process.GetProcessesByName("application name");
IntPtr windowhandle = IntPtr.Zero;
if (processes.Length == 1)
{
   foreach (var process in processes )
   {
       windowhandle = process.MainWindowHandle;
   }
}

messageBoxResult = NativeMethods.MessageBox(
   windowhandle, 
   text, 
   "Title", 
   (int)(NativeMethods.MB_OK | NativeMethods.MB_ICONINFORMATION | NativeMethods.MB_TOPMOST));
相关问题