Get Control/Form object from IntPtr Handle

inva picture inva · May 9, 2012 · Viewed 9.4k times · Source

I try to get the managed control from a shown Word Application window using following code:

Process[] processes = null;
processes = Process.GetProcessesByName("WINWORD");
Process wordProc = processes[0];
Control wordControl = Control.FromHandle(wordProc.MainWindowHandle);

unfortunately wordControl is always null... as far as i know, FromHandle returns null, if no handle related control was found. But actually I guess there should be a related control, because I can see the window on my screen.

Therefore my question is, if I'm doing something terribly wrong while trying to get the handle or the control. Or maybe my general approach will not work for some, at this time unknown, reasons based somewhere in the .NET / Windows environment.

Answer

Rich picture Rich · May 9, 2012

What you are trying to do is not possible. You cannot take an instance of Word running in its own process and cast it as a C# WinForms Control - this would be totally insecure.

Depending on what you want to do, there are two approaches you can take:

  • If you want to affect the behaviour of an existing Word instance, then you can send it some messages using SendMessage() and other assorted User32.DLL functions. Use Pinvoke / DLL Import to accomplish this.

  • If you are trying to use Word functionality in an app you have written (e.g. create word document) then use Word interop libraries:

Edit

If you're interested in handling key events in an existing Word instance, you can use a Low Level keyboard hook to deal with key events, specifying the handle of the word procs you're interested in.