
[英]Open multiple instances of MessageBox and automatically close after several seconds
[英]How to close MessageBox automatically after a couple of seconds without using definition of the AutoClosingMessageBox class?
我一直坚持在计时器到期后自动关闭MessageBox
。 我使用static
类型的Timer
变量(不是System.Windows.Forms.Timer
),它在特殊的class
中定义( class
的定义不是static
)。
由于static
关键字,计时器在对 class 名称的引用的帮助下调用。 我的class
,其中这个定时器定义为static
,称为Helper
。 所以我使用下一个代码产生的调用
Helper.timer.Interval = 300000;
Helper.timer.Enable = true;
timer 是这个变量的名字
任务是处理MessageBox
出现的时间,在时间到期后,如果没有点击其中的任何按钮,则自动关闭此MessageBox
。 是否可以在不使用和定义AutoClosingMessageBox
class 的情况下执行此操作,就像我在模拟问题中看到的那样?
我已经尝试了一些方法,包括检查用户是否单击了MessageBox
的某些按钮,但它没有给我所需的结果。
如果有人能告诉我实现,我将不胜感激:) 如果需要,我可以用我整个项目的代码模板填写问题。 这都是我需要在 C# 编程语言上创建的。
提前致谢!
一种对我有用的方法是创建一个临时的(不可见的)window 来托管MessageBox
。 此临时 window 作为owner
参数传递给Show
方法。 当所有者Form
在等待Task.Delay
之后被处理时,消息框也应该被处理。
public MainForm()
{
InitializeComponent();
buttonHelp.Click += onHelp;
}
private async void onHelp(object sender, EventArgs e)
{
var owner = new Form { Visible = false };
// Force the creation of the window handle.
// Otherwise the BeginInvoke will not work.
var handle = owner.Handle;
owner.BeginInvoke((MethodInvoker)delegate
{
MessageBox.Show(owner, text: "Help message", "Timed Message");
});
await Task.Delay(TimeSpan.FromSeconds(2));
owner.Dispose();
}
此链接对您有帮助吗?
此链接导入并实现“ User32.dll ”,用于自动关闭消息框。 User32.dll是一个库,提供用于控制 windows 或操作系统中的菜单等项目的功能。
如果超过时间,可以通过“ FindWindow ”获取消息框句柄,然后通过“ SendMessage ”关闭消息框。
我参考链接的内容编写了一个简单的示例程序。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Timer CloseTimer { get; } = new Timer();
private string Caption { get; set; }
private void Form1_Load(object sender, EventArgs e)
{
CloseTimer.Tick += CloseTimerOnTick;
CloseTimer.Interval = 100;
}
private void CloseTimerOnTick(object sender, EventArgs e)
{
// find window
var mbWnd = FindWindow("#32770", Caption);
// check window
if (mbWnd == IntPtr.Zero)
{
// stop timer
CloseTimer.Enabled = false;
}
else
{
// check timeout
if ((DateTime.Now - Time).TotalMilliseconds < Timeout)
return;
// close
SendMessage(mbWnd, 0x0010, IntPtr.Zero, IntPtr.Zero);
// stop timer
CloseTimer.Enabled = false;
}
}
private void btMessage_Click(object sender, EventArgs e)
{
Show(@"Caption", @"Auto close message", 3000);
}
private void Show(string caption, string message, int timeout)
{
// start
CloseTimer.Enabled = true;
// set timeout
Timeout = timeout;
// set time
Time = DateTime.Now;
// set caption
Caption = caption;
// show
MessageBox.Show(message, Caption);
}
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.