C#处理对话框的按钮以另一种形式单击 [英] C# Handle a dialog's button click in another form

查看:106
本文介绍了C#处理对话框的按钮以另一种形式单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个表格.在这种情况下,我必须显示一个带有文本和取消"按钮的对话框(在某些情况下).我想在表单中捕获该按钮的事件,或者知道是否单击了取消按钮.

如何才能做到这一点 ?我相信这应该是可能的,但无法弄清楚怎么办?

更新:实际上,用户不必单击取消"按钮.对话框出现,直到主窗体执行活动为止.如果活动完成,则对话框应由main关闭.如果用户单击取消",则必须由主表单执行其他代码.这是确切的情况.

谢谢

Hi,

I have a form. In that I got to show a dialog (on some circumstances) with Text and a Cancel button. I want to catch the event of that button in my form Or know if that cancel button was clicked.

How can this be done ? I believe this should be possible but can''t make out how ?

UPDATE : Actually not necessary that the user got to click "Cance" button. The dialog appears till the main form performs an activity. If the activity is finished, the dialog should be closed by main. If user clicks cancel then other code has to be performed by the main form. This is the exact scenario.

Thanks

推荐答案

if(DialogResult.Cancel != form.ShowDialog()) { ... }

将取消"按钮的DialogResult属性设置为取消".您还将需要一个OK按钮(DialogResult为OK).并设置表单的AcceptButton和CancelButton属性,因此您可以在字段中键入内容,然后按Enter键以单击确定"(或按Esc键单击取消").
if(DialogResult.Cancel != form.ShowDialog()) { ... }

Set the DialogResult property of the Cancel button to Cancel. You will also want an OK button (with a DialogResult of OK). And set the form''s AcceptButton and CancelButton properties, too, so you can type in the field and press Enter to hit OK (or Esc for Cancel).


您可以设置 AcceptButton [ CancelButton [
You can set AcceptButton[^] and CancelButton[^] property the button in your Form that handles the default Enter and ESC action.

AcceptButton and CancelButton property makes sense when used with Form.ShowDialog().
Remember that just setting the AcceptButton/CancelButton is not enough. This just tell which button should be invoked on ENTER/ESC. We have to set the DialogResult in the Button handler.

button1.DialogResult = System.Windows.Forms.DialogResult.OK;
button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
form1.AcceptButton = button1;
form1.CancelButton = button2;



如果要在关闭表单之前执行一些验证,则可以处理
点击 [ ^ ]事件.

关闭表单后,您可以检查结果.



If you want to perform some validation before the Form close, you then handle Click[^] event on the button.

And when the form is closed you can check on the result.

LoginForm login = new LoginForm();

DialogResult result = login.ShowDialog();

if (result == DialogResult.OK)
{
  MessageBox.Show("User has loggedin");
}
else
{
  MessageBox.Show("User failed validation");
}


这篇关于C#处理对话框的按钮以另一种形式单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆