Search code examples
c#.netvisual-studio-2010desktophwnd

How can you get a Form object from the desktop's handle?


I want to know if it is possible to acquire the desktop's Form. I have tried to get the hWnd from the desktop and use Form.FromHandle to get the form. But it always returns null. So I assume this is not possible; if it is possible can someone show me an example code. Here is the code that did not work below:

 hWnd = GetDesktopWindow();
 desktop = Form.FromHandle(hWnd) as Form;
 System.Diagnostics.Debugger.Break();

P.S. Can someone also explain what I did wrong here.


Solution

  • You can't do this because the desktop window isn't a Form. FromHandle() tries to find the managed Control (in this case a Form) that corresponds to the given window handle. Since no such Control exists, it returns null.