在C#中创建弹出窗体

时间:2013-12-19 19:26:30

标签: c# .net winforms

我正在尝试创建一个窗体,在事件触发时显示2秒钟,然后自动关闭。

我尝试了几种选择。这是我目前的代码:

        this.aletPopup.StartPosition = FormStartPosition.CenterScreen;
        this.aletPopup.Show();
        Thread.Sleep(2000);
        this.aletPopup.Close();

这会预先形成我想要的动作,但是,当表单加载时,它不会加载表单上的标签或图像。相反,图像和标签变得透明的区域。我想要的输出是这样的: enter image description here

我也尝试使用显示图形的this.aletPopup.ShowDialog();。但是,使用此方法时,表单不会自动关闭。

编辑:我正在尝试使用 Michael Perrenoud的解决方案。但是,我无法让表格结束。我有一个设置为2000毫秒间隔的计时器,它被初始禁用。我是否正确地覆盖了OnShown?

public AlertPopForm()
    {
        InitializeComponent();

    }

    private void closingTimer_Tick(object sender, EventArgs e)
    {
        closingTimer.Enabled = false;
        this.Close();
    }

    private void AlertPopForm_OnShown(object sender, System.EventArgs e)
    {
        closingTimer.Enabled = true;
        closingTimer.Start(); 
    }

5 个答案:

答案 0 :(得分:6)

相反,如何利用ShowDialog,然后在对话框表单上使用Timer。在Tick的{​​{1}}事件中,关闭表单。

Timer

如果您想要一些灵活性,甚至可以将间隔传递到对话框表单的this.aletPopup.StartPosition = FormStartPosition.CenterScreen; this.aletPopup.ShowDialog();

这里需要注意的是,您需要利用OnShown覆盖实际.ctor Start,以便实际向用户显示该表单。

答案 1 :(得分:1)

原因可能在Message Loop中。当你通过Thread.Sleep阻塞你的线程时,它也会阻止消息循环。

你可以这样做:

this.aletPopup.StartPosition = FormStartPosition.CenterScreen;
this.aletPopup.Show();
for(var i = 0; i<= 200; i++)
{
    Thread.Sleep(10);
    Application.DoEvents();
}
this.aletPopup.Close();

DoEvents将在此期间处理来自消息队列的消息。

答案 2 :(得分:1)

调用Thread.Sleep时,您正在阻止UI线程,从而阻止它处理UI事件。

您需要确保在2秒后调用Close而不实际阻止主线程。有多种方法可以执行此操作,例如使用Timer或类似Task.Delay的内容:

aletPopup.StartPosition = FormStartPosition.CenterScreen;
aletPopup.Show();
Task.Delay(TimeSpan.FromSeconds(2))
    .ContinueWith(t => aletPopup.Close(), 
    TaskScheduler.FromCurrentSynchronizationContext());

答案 3 :(得分:0)

发生这种情况的原因是,您正在暂停绘制表单的线程。因此表单有时间显示,但正在绘制时,线程正在停止。

很容易修复......

使用以下处理程序为Load事件的弹出窗口添加事件处理程序:

private async void handleLoad(Object sender, EventArgs args)
{
  await Task.Delay(2000);
  Close();
}

<强>备注 因为您使用了Show(),所以用户可以随时点击此弹出窗口。如果这是不合需要的,请改用ShowDialog()

答案 4 :(得分:-1)

您是否尝试刷新以重绘表单?

    this.aletPopup.StartPosition = FormStartPosition.CenterScreen;
    this.aletPopup.Show();

    this.alertPopup.Refresh();


    Thread.Sleep(2000);
    this.aletPopup.Close();
相关问题