背景:我想使用“是/否”按钮向用户显示自定义消息框,如果用户单击其中的每个按钮,我会将结果返回给调用者。此外,如果用户没有再次显示任何反应,我想返回第三个结果(使用Timer
事件)。 一句话,要么经过一段时间,要么在按钮后点击方法(我的代码中为Display
)应该返回一个值;我想等待其中任何一个发生。
问题:UI看起来已冻结,只有Timer
事件触发。
代码将在真实项目中使用(具有血统名称!):
namespace MessageBox
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyForm.Display();
}
}
public class MyForm : Form
{
public MyForm()
{
List<Button> _buttonCollection = new List<Button>();
FlowLayoutPanel _flpButtons = new FlowLayoutPanel();
Panel _plFooter = new Panel();
_plFooter.Dock = DockStyle.Bottom;
_plFooter.Padding = new Padding(5);
_plFooter.BackColor = Color.FromArgb(41, 47, 139);
_plFooter.Height = 75;
this.FormBorderStyle = FormBorderStyle.None;
this.BackColor = Color.FromArgb(20, 37, 105);
this.StartPosition = FormStartPosition.CenterScreen;
this.Padding = new Padding(3);
this.Width = 400;
_flpButtons.FlowDirection = FlowDirection.RightToLeft;
_flpButtons.Dock = DockStyle.Fill;
_plFooter.Controls.Add(_flpButtons);
this.Controls.Add(_plFooter);
Button btnYes = new Button();
btnYes.Click += ButtonClick;
btnYes.Text = "Yes";
Button btnNo = new Button();
btnNo.Click += ButtonClick;
btnNo.Text = "No";
_buttonCollection.Add(btnYes);
_buttonCollection.Add(btnNo);
foreach (Button btn in _buttonCollection)
{
btn.ForeColor = Color.FromArgb(170, 170, 170);
btn.Font = new System.Drawing.Font("Eurostile", 12, FontStyle.Bold);
btn.Padding = new Padding(3);
btn.FlatStyle = FlatStyle.Flat;
btn.Height = 60;
btn.Width = 150;
btn.FlatAppearance.BorderColor = Color.FromArgb(99, 99, 98);
_flpButtons.Controls.Add(btn);
}
}
static Task taskA;
private void ButtonClick(object sender, EventArgs e)
{
_event.Set();
Button btn = (Button)sender;
if (btn.Text == "Yes")
Result = 1;
else
{
Result = 2;
}
this.Close();
this.Dispose();
}
static AutoResetEvent _event = new AutoResetEvent(false);
private static MyForm form;
public static int Display()
{
form = new MyForm();
StartTimer();
form.Show();
_event.WaitOne();
form.Close();
form.Dispose();
return Result;
}
private static void StartTimer()
{
_timer = new System.Timers.Timer(10000);
_timer.Elapsed += SetEvent;
_timer.AutoReset = false;
_timer.Enabled = true;
}
private static System.Timers.Timer _timer;
public static int Result { get; set; }
private static void SetEvent(Object source, System.Timers.ElapsedEventArgs e)
{
_timer.Start();
Result = -1;
var timer = (System.Timers.Timer) source;
timer.Elapsed -= SetEvent;
_event.Set();
}
}
}
注意:我知道问题是UI控件是在冻结的线程中创建的,但解决方案是什么?