簡體   English   中英

c#WinForms-從靜態引用顯示隱藏的窗口

[英]c# WinForms - Showing hidden window from static reference

我在WinForms項目中傳遞對Windows的引用然后檢索它們時遇到問題。 當我創建另一個(主)表單並在按鈕事件中隱藏登錄表單時,我有了登錄表單(我不想在這里破壞登錄引用,因此將其保留在靜態類中):

private void btnLog_Click(object sender, EventArgs e)
            {
                if (CheckIfPasswordIsCorrect((int)DataSetUsers.Tables[0].Rows[cmbUsers.SelectedIndex][0]
                                            , txtPassword.Text.Trim()))
                {
                    GlobalData.LoginFormRef = this; //passing reference to Login form into static class
                    this.Hide(); //hidding Login form

                    MainForm mainForm = new MainForm();
                    mainForm.Show();
                }
                else
                {
                    MessageBox.Show("Wrong password");
                    txtPassword.Focus();
                }
            } 

GlobalData是帶有靜態對象GlobalData.LoginFormRef的靜態類,因此我可以保留我的Login表單引用。

然后,如果我從主表單注銷並想返回登錄表單,則會收到錯誤消息,或者只是我的應用程序關閉了:

private void btnLogOut_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
            {
                GlobalData.LoggedUser = null;

                if (GlobalData.LoginFormRef != null)
                {
                    GlobalData.LoginFormRef.Show(); //trying to show my login form back
                }

                this.Close(); //closing Main form
                this.Dispose(true); //destroying main form
            } 

當我關閉Main表單並嘗試調用Login表單時,它會立即消失,或者出現錯誤System.ObjectDisposedException。 我不明白為什么。 我在靜態類中有對Login表單的引用。我如何銷毀主表單並再次顯示Login表單?

您是否可能通過使用Application.Run(new MainForm())啟動了應用程序?

如果您這樣做了,那么它將使用關閉UI線程的事件處理程序為MainForm注冊關閉事件。 這將處理所有表單,包括您的登錄表單(並假設您沒有任何活動的非后台線程,則退出應用程序)。

請參閱msdn中有關Application.Run(Form)的備注: https ://msdn.microsoft.com/zh-cn/library/ms157902( v= vs.110) .aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM