I am developing a Windows application using C# - VS2005. Is there a way to get a reference to the main application form ( the one that was started by the application.run()) from any user controls, any objects within the Windows application?
Thanks in advance
I've also stumbled upon this problem today, and I wanted to know the community that I'm interested as well, because maybe it gets an answer faster I thought of storing it somewhere, but I don't know where to store it in order for it to be visible to all the application's classes (in the same assembly with it). Moreover, it cannot be stored in a static variable for obvious reasons. I also thought of writing a class with a single public static property, but you need to pass an argument to the static constructor of the class, and I'm afraid that is impossible (at least, to my knowing). Anyone, any thoughts on this, please?
Why can the main Form instance not be stored in a static "variable" (rather, a field)? This is acceptable so long as no other control sets the field or property. If you're worried about other assemblies setting it, make the field internal and a read-only property that returns the field.
You could also use Process.GetCurrentProcess().MainWindowHandle to get a handle (an IntPtr) to th emain window, then you could get a Control reference using Control.FromHandle() and pass that IntPtr representing the window handle. That will at least give you a Control reference you can pass to other methods.
I tried the Process.GetCurrentProcess() way, and it fails, when I call it like this:
It says "The specified cast is not valid". Right now I'm a little puzzled about this Anyone, any ideas please?
I came up with the idea of displaying the window's title, so it seems that it displays the title of the current window (meaning that, MainWindow is, in fact, the current window ?) and NOT the title of the MAIN window (from which Application.Run() was called).
The cast isn't valid. That's why I said you could at least get a Control reference to be passed to methods that require a Control reference. Casting from a basic Control to your Form derivative - called down-casting - is not supported in this way. Control.FromHandle instantiates and wraps a Control around a native HWND (represented as an IntPtr). You could only cast Control to frmMain if the control was instantiated as frmMain or a derivative of frmMain.
Read section 6.1.4 Implicit reference conversions in the C# specification, or sections 8.8 Widening Conversions and 8.9 Narrowing Conversions in the VB.NET specification for more information.