C# 设置所有MessageBox弹窗置顶
时间: 2023-07-12 08:35:05 浏览: 203
让MessageBox弹出在当前窗体的中央(C#)
5星 · 资源好评率100%
你可以使用以下代码将所有的MessageBox弹窗置顶:
```
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetForegroundWindow(IntPtr hWnd);
public static DialogResult ShowTopMostMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
var topMostMessageBox = new Form
{
TopMost = true,
MaximizeBox = false,
MinimizeBox = false,
ShowInTaskbar = false,
FormBorderStyle = FormBorderStyle.FixedDialog,
StartPosition = FormStartPosition.CenterScreen,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink
};
topMostMessageBox.Controls.Add(new Label { Text = text, Dock = DockStyle.Fill, Margin = new Padding(10) });
var okButton = new Button
{
DialogResult = DialogResult.OK,
Text = "OK",
Dock = DockStyle.Bottom,
Margin = new Padding(10)
};
topMostMessageBox.Controls.Add(okButton);
topMostMessageBox.Text = caption;
topMostMessageBox.ShowIcon = icon == MessageBoxIcon.None ? false : true;
topMostMessageBox.Icon = SystemIcons.Question;
SetForegroundWindow(topMostMessageBox.Handle);
return topMostMessageBox.ShowDialog();
}
```
然后,你可以像这样调用它:
```
ShowTopMostMessageBox("This is a message", "Caption", MessageBoxButtons.OK, MessageBoxIcon.Information);
```
阅读全文