How to get a window or process handler for a particular excel process?

How can we get the application window handle or excel process handler that belongs to the excel application instance we created? We use Interop.Excel.dll version 1.3.0.0. The application class does not seem to have an HWnd property to call.

Please note that the solution is not just to find all processes named excel.exe, because we have many excel instances running in parallel, and we want to close only one instance.

Excel.Application app = new Excel.Application(); // .. do something with excel here app.Quit(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); // this is in some cases still not enough to get excel killed uint processID; GetWindowThreadProcessId((IntPtr)hWnd, out processID); // how to get HWnd from this Excel application? Process.GetProcessById((int)processID).Kill(); 
+4
source share
4 answers

Although all the answers I received did not help, thanks for the answers anyway. Now I have found a workaround:

Now I created a workflow , which periodically checks excel processes that are older than one minute . Since my excel processing should not last longer than one minute, I can be sure that excel processes older than one minute are done, so I can kill this process.

Another way that comes to my mind is to get a list of all the excel processes before that you create for your excel process. Then after creating the instance, check again . The new PID is the new excel process. Remember to place a lock in it to fix multithreading issues.

+1
source

The application class does not have an HWnd property to call

The Excel.Application class has the Hwnd property.

In response to the comment:

We do not use Microsoft.Office.Interop.Excel.dll, but instead Interop.Excel.dll, which lacks this property

I would recommend using PIA (Microsoft.Office.Interop.Excel.dll). If you have a good reason not to want this, and the RCW that you use for some reason does not reveal the property, an alternative could be to use late binding, for example:

 typeof(Excel.Application).InvokeMember("Hwnd", BindingFlags.GetProperty, null, app, null); 
+2
source

You can use this construct to call the Windows API function

  [DllImport("user32.dll")] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); IntPtr hWnd = FindWindow("XLMAIN", null); 

But you must do this BEFORE any operations with the Application object - create it, set Visible = true and with the next line of code get handle

0
source

Good morning everyone,

I use hWnd = FindWindow ("XLMAIN", 0), but it returns me 0 while the Excel worksheet is open! the call is a VB6 form, and the office version is 2010, 32 bits. Should I change lpClassName, which is no longer "XLMAIN"?

Thanks a lot in advance

INTELED

0
source

Source: https://habr.com/ru/post/1336306/


All Articles