You can use MSIL code to call Win32 APIs and one of the simplest example of it is by closing an application programmatically. In this small article, author shows you how to close the Calculator application by using MSIL code.
Calling Win32 APIs in Win32 ASM is pretty easy. No matter if you use Visual Basic .NET or C#.
In the following code, we call FindWindow and PostMessage APIs using ILASM to close an application.
First of all, open the calculator application from accessories and do the following:
save as turnoffcalc.il
ilasm turnoffcalc.il /exe
Now here is the complete list of code, which will close the calculator application.
.module extern user32.dll
.assembly IllAwesomeDidItAgain{}
.class public AVoff
{
.method public hidebysig static pinvokeimpl("user32.dll" winapi)
int32 FindWindow(string classname,string windowname) cil managed preservesig
{
}
.method public hidebysig static pinvokeimpl("user32.dll" winapi)
int32 PostMessage(int32 wind,int32 msg,int32 param,int32 paramm) cil managed preservesig
{
}
.method public static void Main() cil managed
{
.entrypoint
.maxstack 4
.locals (int32 Valx)
ldnull
ldstr "Calculator"
call int32 AVoff::FindWindow(string,string)
stloc.0
ldloc.0
ldc.i4.s 16
ldc.i4.0
ldc.i4.0
call int32 AVoff::PostMessage(int32,int32,int32,int32)
pop
ret
}
}
Run the output program then you'll notice that calculator is closed.