简体   繁体   English

C#Windows窗体关闭

[英]C# Windows Form Close

I have a C# windows form Menu based application in .Net framework 4.0. 我在.Net Framework 4.0中有一个基于C#Windows窗体Menu的应用程序。 in my option there are too many controls are added in form. 在我的选择中,表单中添加了太多控件。 a DataGridView is my first control on form. DataGridView是我在窗体上的第一个控件。 I handled a event on DataGridViewCellDoubleClick , in this event I am set values of all controls, and too many events are fire from this event and too many method is also called from this event. 我在DataGridViewCellDoubleClick上处理了一个事件,在此事件中,我设置了所有控件的值,并且此事件触发了太多事件,并且此事件也调用了太多方法。

My question is i double click on DataGridViewCell then immediately i click on my form exit button. 我的问题是我双击DataGridViewCell然后立即单击表单退出按钮。 my form is immediately close but my CellDoubleClick event is fired and it is executing and i have too many problems and exceptions occur because form is closed but my code is executing. 我的表单立即关闭,但是我的CellDoubleClick事件被触发并正在执行,并且我遇到了太多的问题,因为表单已关闭但我的代码正在执行,所以发生了异常。

How can I resolve this problem that either form not close when my event is completely execute, or my event is should not execute or i can do some code in Closing event of form that prevent me from this problem. 我该如何解决这个问题,即当事件完全执行时表单没有关闭,或者我的事件不应该执行,或者我可以在表单的Closing事件中执行一些代码来防止出现此问题。

监听FormClosing事件,然后在后台进程繁忙时将e.Cancel = true设置e.Cancel = true

Add this login in your code... I hop this will work. 将此登录名添加到您的代码中...我希望它可以工作。

bool inProcess = false;

private void DataGridViewCellDoubleClick(...)
{
   inProcess = true;
   //Write all ur code
   inProcess = false;
}

private void Form_Closing(...)
{
   e.Cancel = inProcess;
}

@Shell is on the right track, but to close the form when the code is finished instead of cancelling the Form_Close try this: @Shell处于正确的轨道,但是在代码完成后关闭表单,而不是取消Form_Close,请尝试以下操作:

bool inProcess = false;

private void DataGridViewCellDoubleClick(...)
{
    inProcess = true;
    //Write all your code
   inProcess = false;
}

private void Form_Closing(...)
{
    while(inProcess)
    {
    Application.DoEvents();
    }
}

After some research based on the commentor's hint I have to add that your form would not be disabled during the while-loop, so that there is plenty of opportunity for the user to mess up your execution order. 在基于注释者的提示进行了一些研究之后,我必须补充一点,在while循环期间不会禁用您的表单,因此用户有很多机会来弄乱您的执行顺序。 If you would hide the form or disable all controls before entering the while-loop this would be less severe, but using a seperate thread is the proper way to go. 如果要在进入while循环之前隐藏该窗体或禁用所有控件,则情况可能不会那么严重,但是使用单独的线程是正确的方法。

如果要退出应用程序(如果主窗体上有数据网格),而不仅仅是退出窗口,则可以使用Application.ExitThread方法-ExitThread()或Application.Exit()方法(如果您具有IsBackground属性)设置为true将会杀死进程线程,并应停止触发事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM