During the lifetime of a .NET process, does the handle of a System.Windows.Forms.Form
, lets say the main form used in Application.Run(form)
actually change it's value, i.e. if using the value of the handle in a different process, e.g. IntPtr handle = User32.FindWindow(null, "Name")
, is there a case where that handle might be invalidated by the .NET runtime?
EDIT
I need to know the handles because I want to use SendMessage
and WM_COPYDATA
and the like for IPC.
A window handle is guaranteed to be valid and not get reused for as long as the window lives. It's index like in nature, valid globally and generally behaves more like a global ID than like a kernel handle(which are only valid in one process and pointer like in nature). Once the window gets closed the window handle might get reused and now points to another window.
But what's not obvious is if the lifetime of the Form
and the underlying windows window
are the same. I vaguely remember that in Delphi's VCL(Which is the spiritual predecessor of Windows.Forms) certain property changes recreated the window in the background.
The existence of the Control.RecreatingHandle property seems like a strong indication that indeed the lifetime of the underlying window can be shorter than the lifetime of the .net control. Which could lead to the handle of a Form
changing during its lifetime.
Control.RecreateHandle
The RecreateHandle method is called whenever parameters are needed for a new control, but using a call from UpdateStyles to CreateParams is insufficient. This method also calls DestroyHandle and CreateHandle and sets RecreatingHandle to true.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.recreatehandle.aspx
From the description of this method I conclude that the window handle can indeed change during the lifetime of the form.
来源:https://stackoverflow.com/questions/6772634/can-a-window-handle-in-net-change-its-value