Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Control/Form object from IntPtr Handle

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.

like image 466
inva Avatar asked May 20 '26 15:05

inva


2 Answers

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.

like image 195
Rich Avatar answered May 23 '26 05:05

Rich


Control.FromHandle requires you to pass the handle of the managed control, not the MainWindowHandle of the win32 window...

like image 29
animaonline Avatar answered May 23 '26 03:05

animaonline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!