Reputation: 4928
This what i am trying to achieved
if( this.BeginInvoke((Action)(
() => MessageBox.Show("Test",
MessageBoxButtons.YesNo) == DialogResult.No)))
The above gives error. I try seperating the delegate to an outside method like
delegate void test(string text);
private void SetTest(string text)
{
if(MessageBox.Show(text,"", MessageBoxButtons.YesNo) == DialogResult.No)
}
But it breach the very reason why i need the delegate. I found out the first works for me but i don't know how to put it in an if/else statement. Pls any help in a better way i can achieve some thing like below would be appreciated.
if(this.BeginInvoke((Action)(
() => MessageBox.Show("Test",
MessageBoxButtons.YesNo) == DialogResult.No)))
Upvotes: 1
Views: 2438
Reputation: 39122
Another variation....man this is ugly:
if ((bool)this.Invoke((Func<bool>)delegate
{
return MessageBox.Show("Test Message",
"Test Title",
MessageBoxButtons.YesNo) == DialogResult.No;
}))
{
Console.WriteLine("No was indeed selected.");
}
This should work on any version of 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.");
}
}
EDIT: You could refactor that code into something more useful...
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);
}
}
Upvotes: 2
Reputation: 34407
It seems like you need an Invoke()
method, not BeginInvoke()
:
var messageBoxResult = (DialogResult)Invoke(new Func<DialogResult>(
() => MessageBox.Show("Test", "Test", MessageBoxButtons.YesNo)));
if(messageBoxResult == DialogResult.No)
{
}
BeginInvoke
executes delegate asynchronously, meaning that the result is not immediately available on the thread which calls BeginInvoke
.
Upvotes: 2
Reputation: 11763
Why not make your (and your fellow coders) life easier, and do something like:
var user_said_no = this.BeginInvoke((Action)(
() => MessageBox.Show("Test", MessageBoxButtons.YesNo) == DialogResult.No));
And then have:
if (user_said_no)
cancel_nuclear_attack() ; // Or whichever things you need to do.
Upvotes: 1