Recently I got a query from a reader to know how to kill an application if it is running in Windows Mobile 5.0, this is a very interesting question .To do this you need to capture the snapshot of current processes by calling CreateToolhelp32Snapshot API and then get each process name from the process list finally kill the process if its matches with the application name passed as parameter
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
public class Class1
{
[DllImport("toolhelp.dll")]
public static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processid);
[DllImport("coredll.dll")]
private static extern IntPtr OpenProcess(int flags, bool fInherit, int PID);
private const int PROCESS_TERMINATE = 1;
[DllImport("coredll.dll")]
private static extern bool TerminateProcess(IntPtr hProcess, uint ExitCode);
[DllImport("CoreDll.dll")]
private extern static Int32 CloseHandle(IntPtr hProcess);
private const int TH32CS_SNAPPROCESS = 0×00000002;
private const int PROCESS_TERMINATE = 1;
private const int INVALID_HANDLE_VALUE = -1;
public Class1()
{
}
public void ShutDownApp(string appName)
{
//get the sanpshot of the processlist
IntPtr handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if ((int)handle > 0)
{
byte[] data, tempBuffer;
data = new byte[564];
tempBuffer = BitConverter.GetBytes(564);
Buffer.BlockCopy(tempBuffer, 0, data, 0, tempBuffer.Length);
//initialize a empty buffer
byte[] buffer = data;
//get the snapshot of the process
int sanpshotStatus = Process32First(handle, buffer);
while (sanpshotStatus == 1)
{
//Retrive ProcessID,ProcessName
uint ProcessID = BitConverter.ToUInt32(buffer, 8);
//extract the process name
string ProcessName = Encoding.Unicode.GetString(buffer, 36, 256);
ProcessName = ProcessName.Substring(0, ProcessName.IndexOf(”));
if (ProcessName == appName) //if application is running then kill the app
{
IntPtr termProcess;
termProcess = OpenProcess(PROCESS_TERMINATE, false, (int)ProcessID);
if (termProcess != (IntPtr)INVALID_HANDLE_VALUE)
{
TerminateProcess(termProcess, 0);
CloseHandle(termProcess);
break;
}
}
sanpshotStatus = Process32Next(handle, buffer);
}
//Close handle
CloseToolhelp32Snapshot(handle);
}
}
}
Cheers
Anand