How to kill a window?
When I click on an ESRI COM toolbar item, it spawns a window - it looks like a Winform. Since I didn't spawn the window directly, I can't just do an Object.Close() on it. What technique can I use to delete a window my app开发者_运维技巧lication spawned, but that I don't have an object reference of?
I think the easiest way is using p/invoke.
The easiest way: Use FindWindow() function to get and HWND for that window (in C# its IntPtr, you can use NativeWindow class as a wrapper - http://msdn.microsoft.com/en-us/library/system.windows.forms.nativewindow.aspx#Y114)
Once you have the HWND you can use CloseWindow() to close the window or send a message to the window useing SendMessage(youHWND, WM_CLOSE, IntPtr.Zero, IntPtr.Zero) (WM_CLOSE = 0x0010).
If your window has a parent (you can use spy++ to find that out) you can find your window in a more precise way using FindWindowEx().
Hope it helps!
Good luck!
p.s.
Just to be REALLY sure you're not by accident killing another application's window unexpectedly (if you use FindWindow or FindWindowEx without a parent) you can use GetWindowThreadProcessId() to make sure that the window belongs to your process!
Assuming you don't have the window handle you could interop to Win32 and do the following:
In some method call:
CallBackPtr callback = WindowEnumeration;
EnumWindows(callback, IntPtr.Zero);
Then it will call the following to find the window and close it, just replace <title> with as descriptive a title for the window as you can to prevent closing of windows that were not intended to be closed.
private bool WindowEnumeration(IntPtr hwnd, IntPtr lParam)
{
_windowName.Clear();
if (GetWindowText(hwnd, _windowName, _windowName.Capacity) != 0)
{
if (_windowName.ToString().Contains("<title>"))
{
PostMessage(window, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}
return true;
}
The information for calling Win32 can be found in MSDN or pinvoke.net
精彩评论