Reputation: 353
In my current program I have a main window and a secondary window that pops up when a button is pressed. If the secondary window is currently shown but doesn't have focus the button will instead bring it to focus.
At this time I am creating a new instance of the secondary window as the main window loads and simply checking its status with SubWindow.IsDisposed and SubWindow.CanFocus
I have found that if I do not create a new instance at the beginning SubWindow.IsDisposed throws an exception. As long as I'd previously created an instance of SubWindow the check runs fine.
My question- The current version works fine but is there a better way of doing this? It is not a huge concern, but it feels like it'd be better to be able to check for existence without having to guarantee that it has existed at least once before.
Upvotes: 2
Views: 4082
Reputation: 4280
You can have static counter property in your class. Increment on instantiation, decrement on disposal. That's in general... in your case you better follow VoodooChild's advice.
Upvotes: 1
Reputation: 1672
Implement the second window using a singleton pattern.
public class SecondForm : Form
{
public static m_myInstance= new SecondForm();
public static bool m_visible = false;
public SecondForm ()
{
InitializeComponent()
}
public SecondForm Instance()
{
return m_myInstance;
}
public static void Show()
{
...
}
}
Upvotes: 0
Reputation: 353
VoodooChild got me on the right track. (SubWindow == null)
returns false though when the window has opened once and then been closed.
Currently using
(SubWindow == null || SubWindow.IsDisposed)
which works for all cases so far.
Upvotes: 1
Reputation: 9784
You could do a check on SubWindow to see if it is null. If thats the case then instantiate the SubWindow otherwise it exists.
Upvotes: 4