2010年7月29日 星期四

Process class has properties for MainWindowTitle, Id, and ProcessName

Public Class Form1

Private WithEvents processView As New ListView() With {.Dock = DockStyle.Fill, .View = View.Details}
Private Const SW_RESTORE As Integer = 9
Public Declare Function ShowWindow Lib "user32" (ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Boolean

Sub New()
InitializeComponent()
processView.Columns.Add("Process name")
processView.Columns.Add("Process id")
processView.Columns.Add("Main window title")
Me.Controls.Add(processView)
RefreshProcessView()
End Sub

Private Sub RefreshProcessView()
For Each lvi As ListViewItem In processView.Items
DirectCast(lvi, ProcessListViewItem).Dispose()
Next
For Each p As Process In Process.GetProcesses
processView.Items.Add(New ProcessListViewItem(p))
Next
' resize all columns so that all titles and contents can be seen.
For i As Integer = 0 To processView.Columns.Count - 1
processView.Columns(i).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
Dim width As Integer = processView.Columns(i).Width
processView.Columns(i).AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize)
If width > processView.Columns(i).Width Then processView.Columns(i).Width = width
Next
End Sub

' Clear up the processes.
Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
For Each lvi As ListViewItem In processView.Items
DirectCast(lvi, ProcessListViewItem).Dispose()
Next
End Sub

Private Sub processView_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles processView.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim item As ProcessListViewItem = DirectCast(processView.GetItemAt(e.X, e.Y), ProcessListViewItem)
ShowWindow(item.Process.MainWindowHandle, SW_RESTORE)
End If
End Sub
End Class

Public Class ProcessListViewItem
Inherits ListViewItem
Implements IDisposable

Private disposedValue As Boolean = False ' To detect redundant calls
Private m_process As Process
Public ReadOnly Property Process() As Process
Get
Return m_process
End Get
End Property

Sub New(ByVal p As Process)
MyBase.New(p.ProcessName)
Me.SubItems.Add(p.Id.ToString)
Me.SubItems.Add(p.MainWindowTitle)
m_process = p
End Sub

' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
If process IsNot Nothing Then process.Dispose()
End If
End If
Me.disposedValue = True
End Sub

#Region " IDisposable Support "
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region

End Class

沒有留言:

張貼留言