简体   繁体   中英

Using a child window from two different parent windows in c#

My problem deals with the following 3 forms:

MainWindow.cs
SettingsWindow.cs
AuthenticationWindow.cs

Settings window contains information like "Ask for password during startup or not".

I call the Authentication Window from Settings Window in order to remove password (when the password is set).

I call the Authentication Window also during startup (when the password is set).

My Authentication Window interacts with the settings window using a Static variable(To say whether the authentication is successful or not).

But, in order to reuse the same code (that is, to call the same authentication window during startup), I am unable to tell the MainWindow whether the authentication is successful or not. However, I must some how reuse the code.

My question is: Is it possible to notify the Child Window about whom the parent window is? If yes, Sample code please...

Hope my question is clear.

Kindly help!

ChildWindow c1=new ChildWindow();
c1.Owener=authenticationWindow;
c1.Show();  //or ShowDialog();

ChildWindow c2=new ChildWindow();
c1.Owener=anotherWindow;
c2.Show();  //or ShowDialog();

//to get the parent, use the property c.Owner
if(c.Owner is AuthenticationWindow)  //AuthenticationWindow is the type of authenticationWindow instance
{
 ...
}

I assume that Authentication Window is being used with ShowDialog() along the lines of:

AuthenticationWindow auth = new AuthenticationWindow();
if (auth.ShowDialog(this) == DialogResult.Ok)
{
    // we know it was successful
}

Then within AuthenticationWindow when you've had success you'll call:

       DialogResult = DialogResult.Ok;
       Close();

to get the feedback above, or to signal that it failed by

       DialogResult = DialogResult.Cancel;
       Close();

Alternatively, you could set a property on AuthenticationWindow:

class AuthenticationWindow : Form
{
     public bool Success { get; set;}


}

and set the value of Success appropriately from within the AuthenticationWindow code.


Lastly, if you want immediate feed back to be sent to your other windows, consider implementing an event:

class AuthenticationWindow : Form
{
     public event Action<bool> SignalOutcome;

     private OnSignalOutcome(bool result)
     {
          Action<bool> handler = SignalOutCome;
          if (handler != null) handler(result);
     }
}

Then you will have to subscribe to that event where you call the Authentication window:

AuthenticationWindow auth = new AuthenticationWindow();
auth.SignalOutcome += (outcome) => { /* do something with outcome here */ };

auth.ShowDialog(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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