另一个变体......这很丑陋:
if ((bool)this.Invoke((Func<bool>)delegate
{
return MessageBox.Show("Test Message",
"Test Title",
MessageBoxButtons.YesNo) == DialogResult.No;
}))
{
Console.WriteLine("No was indeed selected.");
}
这应该适用于任何版本的 C#:
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread T = new System.Threading.Thread(Foo);
T.Start();
}
delegate bool SetTestDelegate(string text);
private bool SetTest(string text)
{
return (MessageBox.Show(text, "", MessageBoxButtons.YesNo) == DialogResult.No);
}
private void Foo()
{
if ((bool)this.Invoke(new SetTestDelegate(SetTest), new object[] {"test"}))
{
Console.WriteLine("No was indeed selected.");
}
}
编辑:您可以将该代码重构为更有用的东西......
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread T = new System.Threading.Thread(Foo);
T.Start();
}
private void Foo()
{
if (Response("test") == System.Windows.Forms.DialogResult.No)
{
Console.WriteLine("No was indeed selected.");
}
}
delegate DialogResult ResponseDelegate(string text);
private DialogResult Response(string text)
{
if (this.InvokeRequired)
{
return (DialogResult)this.Invoke(new ResponseDelegate(Response), new object[] { "test" });
}
else
{
return MessageBox.Show(text, "", MessageBoxButtons.YesNo);
}
}