Introduction
This article focuses on a small piece of code that actually simulates the EndTask
function. By using this, we can force end an EXCEL.EXE process once we are done using the object.
Background
Excel objects created using MS Office Excel 2003 and below versions are basically COM objects. When we instantiate an object from code, it creates an EXCEL.EXE process in the system processes. This corresponds to a single instance of Excel. The .NET CLR is not responsible for releasing COM objects. All it can do is reduce the reference count of COM objects, which would then be cleared off by the GC, which is again not under the control of the developer as the GC could run at any instant. So there is no means of releasing an Excel object from the memory immediately. Once there are many EXCEL.EXE appearing in the Task Manager, it may end up in lack of memory errors.
Using the code
We would use the EndTask
method of user32.dll to simulate the end task functionality which will release the EXCEL.EXE from the memory (Task Manager).
You need to import the EndTask
method as shown below:
//method import
Private Declare Function EndTask Lib "user32.dll" Alias _
"EndTask" (ByVal hwnd As Long) As Long
//Getting the window handle for the excel
If (objExcel.Version) < "10.0" Then
iHandle = FindWindow(Nothing, ObjExcel.Caption)
Else
iHandle = objExcel.Parent.Hwnd
End If
//Calling the EndTask Method
intResult = EndTask(iHandle)
Points of Interest
You would not require any special permissions to access the EndTask
method. So if you can create the Excel object, you can very easily destroy it using this piece of code.