Google Analytics

Search This Blog

Tuesday, February 19, 2013

Reference Startup Form (VB.Net)

This applies to Microsoft .NET framework.

To reference startup form of a windows form application, there are 3 simple methods.

Assuming the startup form is called Form1.vb

Method 1:

Dim objFrmMain as Form1

objFrmMain = My.Application.ApplicationContext.MainForm
This will only work when the form is loaded, it returns nothing under non-GUI context such timer's interval event.

It returns nothing before the form instance is fully loaded, i.e during 'New' context.



Method 2:

Dim objFrmMain as Form1

objFrmMain = My.Application.OpenForms.Item("Form1")
This works under timer's interval event.

It will also return nothing before the form instance is fully loaded, i.e during 'New' context.

Method 3:

Dim objFrm as Form
Dim objFrmMain as Form1

objFrm = Control.FromHandle(Process.GetCurrentProcess.MainWindowHandle)

If Not objFrm Is Nothing Then

   If objFrm .Name = "Form1" Then 
      objFrmMain = DirectCast(objFrm,Form1) 
   Else 
      msgbox("Startup form is not the active window!") 
   End if

End if


This works under all context. Nonetheless, it will only return the reference of startup form if it is the active window - an active window is the window which currently has the focus. i.e in the event a message box is popped up, the active window is the message box.

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainwindowhandle.aspx

Conclusion:

Use method 2.

2 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.