使用最少的代码,完成窗体关闭任务 - C#学习资料-采集之家


C#学习资料>>使用最少的代码,完成窗体关闭任务

使用最少的代码,完成窗体关闭任务

发布:2010, January 1, 11:19 PM 浏览:799

有两个窗体,form1,form2,在form1中button1有一个单击的方法,弹出form2.现在需要的是得到正确的 DialogResult .form1里的主要代码如下,从这里可以看出结果是否正确.

C#代码
  1. private void button1_Click(object sender, EventArgs e)   
  2.        {   
  3.            Form1 f2 = new Form2();   
  4.            DialogResult dr = f2.ShowDialog();   
  5.            if (dr == DialogResult.OK)   
  6.            {   
  7.                MessageBox.Show("OK");   
  8.            }   
  9.            else  
  10.                MessageBox.Show("Cancel");   
  11.        }  

现在form2中有两个button,单击分别要返回如下结果. 

C#代码
  1. private void button1_Click(object sender, EventArgs e)   
  2.         {   
  3.             this.DialogResult = DialogResult.OK;   
  4.         }   
  5.   
  6.         private void button2_Click(object sender, EventArgs e)   
  7.         {   
  8.             if (MessageBox.Show("确认退出""确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)     
  9. {    
  10.  this.DialogResult = DialogResult.Cancel;   
  11.                   }   
  12.   
  13.               
  14.         }  

在这里,点击button2要有提示的,也就是同意了之后,就返回  DialogResult.Cancel

最后需要的一点是,要在点击窗口的右上角的关闭时,也要有如 button2 的提示.如

C#代码
  1. private void Form2_FormClosing(object sender, FormClosingEventArgs e)   
  2.         {   
  3.                            if (MessageBox.Show("退出""?", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)  e.Cancel = true;     
  4.   
  5.                   }  

也就是说,最后我需要做的是得到正确的提示信息,并返回正确的结果.但是,目前的 this.DialogResult后会再次引发FormClosing事件.也就陷入了循环之中,那么,如何才能避免这问题并达到最终的效果呢? 注意,不要使用全局变量的参数之类的.

 

解决办法如下

C#代码
  1.       private void button1_Click(object sender, EventArgs e)   
  2.       {   
  3.           this.DialogResult = DialogResult.OK;   
  4.       }   
  5.   
  6.       private void button2_Click(object sender, EventArgs e)   
  7.       {   
  8.           this.Close();   
  9.       }   
  10.   
  11.       private void Form2_FormClosing(object sender, FormClosingEventArgs e)   
  12.       {   
  13. if(this.DialogResult == DialogResult.OK) return;   
  14.        if (MessageBox.Show("退出""?", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)  e.Cancel = true;     
  15.       }  

这里需要说明的一点是,当窗体关闭时,默认的是DialogResult.Cancel,所以在窗体关闭时的提示全放在了FormClosing 里,让程序自己去判断.


相关信息

评论内容 (必填):

(*请输入图片后三位数字)

Copyright © 2007-2009 采集之家 All Rights Reserved. Powered by SaBlog XHTML 1.0. 清除Cookies. 陕ICP备07009732号