The "Kill Process" tool helps to kill the ASP.NET Development Server instances by port number. The below are the features of this tool.
1. On load the tool displays the running ASP.NET web server instance name and port number
2. Select the port number to kill and click on “Kill Me” button. Kills the selected process.
3. Click on column All it selects all and we can kill all running processes at a time.
4. On form minimize, the notification icon will be displayed in the sys tray.
Below is the code.
Program.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace KillWebServerProcess { static class Program { ////// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new KillWebServer()); } } }
KillWebServer.Designer.cs:
namespace KillWebServerProcess { partial class KillWebServer { ////// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// "disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof(KillWebServer)); this.btnKillMe = new System.Windows.Forms.Button(); this.killme_NotifyIcon = new System.Windows.Forms.NotifyIcon(this.components); this.ExitContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.grpBox = new System.Windows.Forms.GroupBox(); this._all = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this._processname = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this._port = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.killmeProcessView = new System.Windows.Forms.ListView(); this.ExitContextMenu.SuspendLayout(); this.grpBox.SuspendLayout(); this.SuspendLayout(); // // btnKillMe // this.btnKillMe.BackColor = System.Drawing.SystemColors.Control; this.btnKillMe.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnKillMe.Location = new System.Drawing.Point(97, 313); this.btnKillMe.Name = "btnKillMe"; this.btnKillMe.Size = new System.Drawing.Size(95, 23); this.btnKillMe.TabIndex = 5; this.btnKillMe.Text = "Kill Process"; this.btnKillMe.UseVisualStyleBackColor = false; this.btnKillMe.Click += new System.EventHandler(this.btnKillMe_Click); // // killme_NotifyIcon // this.killme_NotifyIcon.ContextMenuStrip = this.ExitContextMenu; this.killme_NotifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("killme_NotifyIcon.Icon"))); this.killme_NotifyIcon.Text = "Kill Process"; this.killme_NotifyIcon.DoubleClick += new System.EventHandler(this.killmeNotifyIcon_DoubleClick); this.killme_NotifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler
(this.killmeNotifyIcon_MouseClick); this.killme_NotifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler
(this.killmeNotifyIcon_MouseDoubleClick); // // ExitContextMenu // this.ExitContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.exitToolStripMenuItem}); this.ExitContextMenu.Name = "ExitContextMenu"; this.ExitContextMenu.Size = new System.Drawing.Size(93, 26); this.ExitContextMenu.Text = "Exit"; // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(92, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // grpBox // this.grpBox.Controls.Add(this.killmeProcessView); this.grpBox.Location = new System.Drawing.Point(2, 0); this.grpBox.Name = "grpBox"; this.grpBox.Size = new System.Drawing.Size(281, 307); this.grpBox.TabIndex = 4; this.grpBox.TabStop = false; // // _all // this._all.Text = "All"; this._all.Width = 38; // // _processname // this._processname.Text = "Process Name"; this._processname.Width = 158; // // _port // this._port.Text = "Port"; this._port.Width = 70; // // killmeProcessView // this.killmeProcessView.CheckBoxes = true; this.killmeProcessView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this._all, this._processname, this._port}); this.killmeProcessView.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.killmeProcessView.FullRowSelect = true; this.killmeProcessView.Location = new System.Drawing.Point(6, 12); this.killmeProcessView.Name = "killmeProcessView"; this.killmeProcessView.Size = new System.Drawing.Size(270, 287); this.killmeProcessView.Sorting = System.Windows.Forms.SortOrder.Ascending; this.killmeProcessView.TabIndex = 3; this.killmeProcessView.UseCompatibleStateImageBehavior = false; this.killmeProcessView.View = System.Windows.Forms.View.Details; this.killmeProcessView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler
(this.killmeProcessView_ColumnClick); // // KillMe // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.BackColor = System.Drawing.Color.MistyRose; this.ClientSize = new System.Drawing.Size(283, 340); this.Controls.Add(this.btnKillMe); this.Controls.Add(this.grpBox); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "KillMe"; this.Text = "Kill Process"; this.Resize += new System.EventHandler(this.killme_Resize); this.ExitContextMenu.ResumeLayout(false); this.grpBox.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnKillMe; private System.Windows.Forms.NotifyIcon killme_NotifyIcon; private System.Windows.Forms.ContextMenuStrip ExitContextMenu; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.GroupBox grpBox; private System.Windows.Forms.ListView killmeProcessView; private System.Windows.Forms.ColumnHeader _all; private System.Windows.Forms.ColumnHeader _processname; private System.Windows.Forms.ColumnHeader _port; } }
KillWebServer.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Diagnostics; using KillWebServerProcess.API; namespace KillWebServerProcess { public partial class KillWebServer : Form { public KillWebServer() { InitializeComponent(); this.Load += new EventHandler(KillMe_Load); } private object _sender = new object(); private EventArgs _e = new EventArgs(); private void KillMe_Load(object sender, EventArgs e) { var processNames = new[] { "WebDev.WebServer", "WebDev.WebServer20", "WebDev.WebServer40" }; var processesKilled = new List<ProcessInfo>(); foreach (var runningProcess in processNames.Select(Process.GetProcessesByName).SelectMany(p => p)) { if (IsRunningProcess(runningProcess)) { var processInfo = new ProcessInfo { Handle = runningProcess.Handle, Id = runningProcess.Id, Name = runningProcess.ProcessName }; if (!processesKilled.Contains(processInfo)) { processesKilled.Add(processInfo); } } } List<SystemProcess> conInfo = TCPUDPAPI.GetTCP().ToList(); List<SystemProcess> results = new List<SystemProcess>(); foreach(ProcessInfo pinfo in processesKilled) { foreach (SystemProcess con in conInfo) { if (pinfo.Id == con.PID) { results.Add(con); } } } foreach (SystemProcess iCon in results) { ListViewItem lvi = new ListViewItem(new[] { "", iCon.PIDName,
iCon.LocalPort.ToString(), iCon.PID.ToString() }) { Tag = iCon, Checked = false }; killmeProcessView.Items.Add(lvi); } } private bool IsRunningProcess(Process process) { return process.HasExited ? false : true; } private void btnKillMe_Click(object sender, EventArgs e) { if (killmeProcessView.CheckedItems.Count > 0) { KillProcess(); } else { MessageBox.Show("Choose a process to kill!", "Warning!"); } } private void KillProcess() { List<SystemProcess> conInfo = TCPUDPAPI.GetTCP().ToList(); foreach (ListViewItem item in killmeProcessView.Items) { if (item.Checked) { KillProcess(item.SubItems[3].Text); } } killmeProcessView.Items.Clear(); KillMe_Load(_sender, _e); } private void KillProcess(string Pid) { var processNames = new[] { "WebDev.WebServer", "WebDev.WebServer20", "WebDev.WebServer40" }; foreach (var selectedProcess in processNames.Select(Process.GetProcessesByName).SelectMany(p => p)) { if (selectedProcess.Id == Convert.ToInt32(Pid)) { selectedProcess.Kill(); SystrayAPI.RefreshNotificationArea(); } } } private void killmeProcessView_ColumnClick(object sender, ColumnClickEventArgs e) { bool uncheck = false; if (e.Column == 0) { foreach (ListViewItem item in killmeProcessView.Items) { if (item.Checked) { uncheck = true; } } foreach (ListViewItem item in killmeProcessView.Items) { item.Checked = (uncheck == true) ? false : true; } } } private void killmeNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) { killmeProcessView.Items.Clear(); KillMe_Load(_sender, _e); if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal; this.Show(); } private void killmeNotifyIcon_MouseClick(object sender, MouseEventArgs e) { killmeProcessView.Items.Clear(); KillMe_Load(_sender, _e); if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal; this.Show(); } private void killmeNotifyIcon_DoubleClick(object sender, EventArgs e) { killmeProcessView.Items.Clear(); KillMe_Load(_sender, _e); if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal; this.Show(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void killme_Resize(object sender, EventArgs e) { if (FormWindowState.Minimized == this.WindowState) { killme_NotifyIcon.Visible = true; this.Hide(); } else if (FormWindowState.Normal == this.WindowState) { killme_NotifyIcon.Visible = false; } } } internal struct ProcessInfo { public Int32 Id; public IntPtr Handle; public string Name; } }
TCPUDPAPI.cs:
using System; using System.Net; using System.Runtime.InteropServices; namespace KillWebServerProcess.API { public class TCPUDPAPI { [DllImport("iphlpapi.dll", SetLastError = true)] static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort,
int ipVersion, TCP_TABLE_CLASS tblClass, int reserved); [DllImport("iphlpapi.dll", SetLastError = true)] static extern uint GetExtendedUdpTable(IntPtr pUdpTable, ref int dwOutBufLen, bool sort,
int ipVersion, UDP_TABLE_CLASS tblClass, int reserved); [StructLayout(LayoutKind.Sequential)] public struct MIB_TCPROW_OWNER_PID { public uint dwState; public uint dwLocalAddr; public uint dwLocalPort; public uint dwRemoteAddr; public uint dwRemotePort; public uint dwOwningPid; } [StructLayout(LayoutKind.Sequential)] public struct MIB_UDPROW_OWNER_PID { public uint dwLocalAddr; public uint dwLocalPort; public uint dwOwningPid; } [StructLayout(LayoutKind.Sequential)] public struct MIB_TCPTABLE_OWNER_PID { public uint dwNumEntries; MIB_TCPROW_OWNER_PID table; } [StructLayout(LayoutKind.Sequential)] public struct MIB_UDPTABLE_OWNER_PID { public uint dwNumEntries; MIB_UDPROW_OWNER_PID table; } enum TCP_TABLE_CLASS { TCP_TABLE_BASIC_LISTENER, TCP_TABLE_BASIC_CONNECTIONS, TCP_TABLE_BASIC_ALL, TCP_TABLE_OWNER_PID_LISTENER, TCP_TABLE_OWNER_PID_CONNECTIONS, TCP_TABLE_OWNER_PID_ALL, TCP_TABLE_OWNER_MODULE_LISTENER, TCP_TABLE_OWNER_MODULE_CONNECTIONS, TCP_TABLE_OWNER_MODULE_ALL } enum UDP_TABLE_CLASS { UDP_TABLE_BASIC, UDP_TABLE_OWNER_PID, UDP_OWNER_MODULE } public static SystemProcess[] GetTCP() { MIB_TCPROW_OWNER_PID[] tTable; int AF_INET = 2; int buffSize = 0; uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET,
TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0); IntPtr buffTable = Marshal.AllocHGlobal(buffSize); try { ret = GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET,
TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0); if (ret != 0) { SystemProcess[] con = new SystemProcess[0]; return con; } MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)
Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID)); IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries)); tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries]; for (int i = 0; i < tab.dwNumEntries; i++) { MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)
Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID)); tTable[i] = tcpRow; rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow)); // next entry } } finally { Marshal.FreeHGlobal(buffTable); } SystemProcess[] cons = new SystemProcess[tTable.Length]; for (int i = 0; i < tTable.Length; i++) { IPAddress localip = new IPAddress(BitConverter.GetBytes(tTable[i].dwLocalAddr)); IPAddress remoteip = new IPAddress(BitConverter.GetBytes(tTable[i].dwRemoteAddr)); byte[] barray = BitConverter.GetBytes(tTable[i].dwLocalPort); int localport = (barray[0] * 256) + barray[1]; barray = BitConverter.GetBytes(tTable[i].dwRemotePort); int remoteport = (barray[0] * 256) + barray[1]; string state; switch (tTable[i].dwState) { case 1: state = "Closed"; break; case 2: state = "LISTENING"; break; case 3: state = "SYN SENT"; break; case 4: state = "SYN RECEIVED"; break; case 5: state = "ESTABLISHED"; break; case 6: state = "FINSIHED 1"; break; case 7: state = "FINISHED 2"; break; case 8: state = "CLOSE WAIT"; break; case 9: state = "CLOSING"; break; case 10: state = "LAST ACKNOWLEDGE"; break; case 11: state = "TIME WAIT"; break; case 12: state = "DELETE TCB"; break; default: state = "UNKNOWN"; break; } SystemProcess tmp = new SystemProcess(localip, localport, remoteip, remoteport,
(int)tTable[i].dwOwningPid, state); cons[i] = (tmp); } return cons; } public static SystemProcess[] GetUDP() { MIB_UDPROW_OWNER_PID[] tTable; int AF_INET = 2; // IP_v4 int buffSize = 0; uint ret = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, AF_INET,
UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0); IntPtr buffTable = Marshal.AllocHGlobal(buffSize); try { ret = GetExtendedUdpTable(buffTable, ref buffSize, true, AF_INET,
UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0); if (ret != 0) {//none found SystemProcess[] con = new SystemProcess[0]; return con; } MIB_UDPTABLE_OWNER_PID tab = (MIB_UDPTABLE_OWNER_PID)
Marshal.PtrToStructure(buffTable, typeof(MIB_UDPTABLE_OWNER_PID)); IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries)); tTable = new MIB_UDPROW_OWNER_PID[tab.dwNumEntries]; for (int i = 0; i < tab.dwNumEntries; i++) { MIB_UDPROW_OWNER_PID udprow = (MIB_UDPROW_OWNER_PID)
Marshal.PtrToStructure(rowPtr, typeof(MIB_UDPROW_OWNER_PID)); tTable[i] = udprow; rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(udprow)); } } finally { Marshal.FreeHGlobal(buffTable); } SystemProcess[] cons = new SystemProcess[tTable.Length]; for (int i = 0; i < tTable.Length; i++) { IPAddress localip = new IPAddress(BitConverter.GetBytes(tTable[i].dwLocalAddr)); byte[] barray = BitConverter.GetBytes(tTable[i].dwLocalPort); int localport = (barray[0] * 256) + barray[1]; SystemProcess tmp = new SystemProcess(localip, localport, (int)tTable[i].dwOwningPid); cons[i] = tmp; } return cons; } } public class SystemProcess : System.Diagnostics.Process { private IPAddress _localip, _remoteip; private int _localport, _remoteport, _pid; private string _state, _remotehost, _proto; public SystemProcess(IPAddress Local, int LocalPort, IPAddress Remote, int RemotePort, int PID, string State) { _proto = "TCP"; _localip = Local; _remoteip = Remote; _localport = LocalPort; _remoteport = RemotePort; _pid = PID; _state = State; } public SystemProcess(IPAddress Local, int LocalPort, int PID) { _proto = "UDP"; _localip = Local; _localport = LocalPort; _pid = PID; } public IPAddress LocalIP { get { return _localip; } } public IPAddress RemoteIP { get { return _remoteip; } } public int LocalPort { get { return _localport; } } public int RemotePort { get { return _remoteport; } } public int PID { get { return _pid; } } public string State { get { return _state; } } public string Protocol { get { return _proto; } } public string RemoteHostName { get { if (_remotehost == null) _remotehost = Dns.GetHostEntry(_remoteip).HostName; return _remotehost; } } public string PIDName { get { return (System.Diagnostics.Process.GetProcessById(_pid)).ProcessName; } } } }
SystrayAPI.cs:
using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.OLE.Interop; namespace KillWebServerProcess.API { internal class SystrayAPI { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle); [DllImport("user32.dll")] static extern bool GetClientRect(IntPtr handle, out RECT rect); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr handle, UInt32 message, Int32 wParam, Int32 lParam); public static void RefreshNotificationArea() { var notificationAreaHandle = GetNotificationAreaHandle(); if (notificationAreaHandle == IntPtr.Zero) return; RefreshWindow(notificationAreaHandle); } private static void RefreshWindow(IntPtr windowHandle) { const uint wmMousemove = 0x0200; RECT rect; GetClientRect(windowHandle, out rect); for (var x = 0; x < rect.right; x += 5) for (var y = 0; y < rect.bottom; y += 5) SendMessage( windowHandle, wmMousemove, 0, (y << 16) + x); } private static IntPtr GetNotificationAreaHandle() { const string notificationAreaTitle = "Notification Area"; const string notificationAreaTitleInWindows7 = "User Promoted Notification Area"; var systemTrayContainerHandle = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Shell_TrayWnd", string.Empty); var systemTrayHandle = FindWindowEx(systemTrayContainerHandle, IntPtr.Zero, "TrayNotifyWnd", string.Empty); var sysPagerHandle = FindWindowEx(systemTrayHandle, IntPtr.Zero, "SysPager", string.Empty); var notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", notificationAreaTitle); if (notificationAreaHandle == IntPtr.Zero) notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", notificationAreaTitleInWindows7); return notificationAreaHandle; } } }