Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » VB.NET » Finding and Listing Processes in Visual Basic 2005

Finding and Listing Processes in Visual Basic 2005


This article shall describe a very simple approach to finding out information regarding the processes currently running on a machine.

Author Rank:
Total page views :  12189
Total downloads :  320
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ApplicationCheckPack_VB.zip
 
Become a Sponsor

Introduction:

 

This article shall describe a very simple approach to finding out information regarding the processes currently running on a machine. The demonstration application includes a collection a methods that may be used to search for specific processes using different criteria or to list out running processes.

 

Such information may be useful for a variety of reason, for example, if an application is dependent upon another application and that primary application must be up and running as a precursor to launching the dependent application, the methods contained in this demonstration will permit the code to test for the presence of the primary application prior to loading the dependent application. If, for example, an application were dependent upon a running copy of calc.exe, the code contained in the demonstration could be used to determine whether or not calc.exe was running prior to allowing the dependent application to run.

 

Alternatively, if an application launches other applications, the methods described herein could be used to determine whether or not that application successfully launched.

 

Everything contained in this demonstration is based upon the use of the framework System.Management library. Aside from what is described in this demonstration, there are many other useful things that may be accomplished through the use of this library, for example one may start or kill processes using elements from System.Management. 

 

This demonstration includes a class containing several methods used to either generate a list of applications or processes running on a machine, or to search for specific processes by means of different search criteria such as the application name, the process name, the process ID, or the process image name. The list related methods also provide information regarding other details about the process such as the memory size or caption bar title. What is demonstrated is only a small subset of the information available.

 

 

Figure 1: Getting a List of Running Applications

 

Getting Started:

 

The solution contains a single Windows Forms project called "ApplicationCheck.vb" which was written in VISUAL BASIC 2005; the application contains a form (Form1.vb) and a class (ProcessValidation.vb).

 

 

Figure 2:  Solution Explorer with the Project Visible

 

Code:  ProcessValidation (ProcessValidation.vb)

 

All of the code used to list processes or search for running processes is contained in the ProcessValidation class.

 

The code for this class begins with the following: 

 

Imports System.Text

Imports System.Management

 

Public Class ProcessValidation       

 

Note that the System.Management library as been added to the imports for this class.  Following the imports, the declaration of the class, the remainder of the class is used to provide the methods used to list process information or to search for the presence of a

 

current process:

 

The class and all contained methods were declared as shared and are therefore immediately available to the application.

 

The first method available in the class is the List All Processes method. This method creates an instance of the Management Class, passing in the argument "Win32_Process". This is then used to populate a management object will a collection of all instances of the class. The list is then built by iterating through the collection and adding the process name and ID to the stringbuilder. The method returns the string to the calling method which is, in this case used to print the list of processes and IDs to a textbox contained in the demonstration application. Note that you can pass other optional arguments to the management class aside from "Win32_Process"; for example, to get a list of services, you can pass in the argument "Win32_Services".

 

''' <summary>

''' Returns a string containing information on running processes

''' </summary>

''' <returns></returns>

''' <remarks></remarks>

 Public Shared Function ListAllProcesses() As String

 

    Dim sb As New StringBuilder()

 

    ' list out all processes and write them into a stringbuilder

    Dim MgmtClass As New ManagementClass("Win32_Process")

    Dim mo As New ManagementObject()

 

    For Each mo In MgmtClass.GetInstances

 

    sb.Append("Name:  " & mo("Name") & Environment.NewLine)

    sb.Append("ID:  " & mo("ProcessId") & Environment.NewLine)

    sb.Append(Environment.NewLine)

    Next

    Return sb.ToString()

 End Function

 

Using a slightly different approach, the next method lists all running applications by first getting a list of all local processes and then checking to see if the process has a visible Main Window Title (by checking to see if the caption bar contains text). If the process contains a window with a caption showing some text, this method will regard it as an open and visible application and will then list out the title, process name, window handle, and memory allocation for that particular process.

 

''' <summary>

''' Returns a string containing information on running processes

''' </summary>

''' <returns></returns>

''' <remarks></remarks>

Public Shared Function ListAllApplications() As String

 

    Dim sb As New StringBuilder()

    Dim p As New Process()

 

    For Each p In Process.GetProcesses(".")

        Try

            If p.MainWindowTitle.Length > 0 Then

                sb.Append("Window Title:  " +

                p.MainWindowTitle.ToString() + Environment.NewLine)

                sb.Append("Process Name:  " + p.ProcessName.ToString() +

                Environment.NewLine)

                sb.Append("Window Handle:  " +

                p.MainWindowHandle.ToString() + Environment.NewLine)

                sb.Append("Memory Allocation: " +

                p.PrivateMemorySize64.ToString() + Environment.NewLine)

                sb.Append(Environment.NewLine)

            End If

 

        Catch

        End Try

        next

 

    Return sb.ToString()

End Function

 

The next method is used to list all processes by image name. This method works in a manner consistent with the previous example but obtains the module information associated with the process and then returns a string containing module level information to include the image name, file path, memory size, and software version. 

 

''' <summary>

''' List all processes by image name

''' </summary>

''' <returns></returns>

''' <remarks></remarks>

Public Shared Function ListAllByImageName() As String

    Dim sb As New StringBuilder()

    Dim p As New Process()

    For Each p In Process.GetProcesses(".")

        Try

            Dim pm As ProcessModule

 

            For Each pm In p.Modules

                sb.Append("Image Name:  " + pm.ModuleName.ToString() +

                Environment.NewLine)

                sb.Append("File Path:  " + pm.FileName.ToString() +

                Environment.NewLine)

                sb.Append("Memory Size:  " +

                pm.ModuleMemorySize.ToString() + Environment.NewLine)

                sb.Append("Version:  " +

                pm.FileVersionInfo.FileVersion.ToString() +

                Environment.NewLine)

                sb.Append(Environment.NewLine)

            Next

        Catch

        End Try

    Next

    Return sb.ToString()

End Function

 

The next method is used to search for a running instance of a process on the local machine by process name. If the method is able to locate the process, it will return a true; if the process is not found, the method will return a false.

 

''' <summary>

''' Determine if a process is running by name

''' </summary>

''' <param name="processName"></param>

''' <returns></returns>

''' <remarks></remarks>

Public Shared Function CheckForProcessByName(ByVal processName As String)

As Boolean

 

    Dim MgmtClass As New ManagementClass("Win32_Process")

    Dim rtnVal As Boolean = False

    Dim mo As New ManagementObject()

 

    For Each mo In MgmtClass.GetInstances()

 

        If mo("Name").ToString().ToLower() = processName.ToLower() Then

            rtnVal = True

        End If

    Next

    Return rtnVal

End Function

 

The next method is used to search for a running instance of a process on the local machine by image name. If the method is able to locate the process, it will return a true; if the process is not found, the method will return a false.

 

''' <summary>

''' Determine if a process is running by image name

''' </summary>

''' <param name="processImageName"></param>

''' <returns></returns>

''' <remarks></remarks>

Public Shared Function CheckForProcessByImageName(ByVal processImageName As String) As Boolean

 

    Dim rtnVal As Boolean = False

    Dim p As New Process()

 

    For Each p In Process.GetProcesses(".")

        Dim pm As ProcessModule

        Try

            For Each pm In p.Modules

                If pm.ModuleName.ToLower() = processImageName.ToLower() Then

                    rtnVal = True

                End If

            Next

        Catch

            ' do nothing

        End Try

    Next

    Return rtnVal

End Function

 

The next method is used to search for a running instance of a process on the local machine by application name. If the method is able to locate the process, it will return a true; if the process is not found, the method will return a false.

 

''' <summary>

''' Determine if an application is running by name

''' </summary>

''' <param name="AppName"></param>

''' <returns></returns>

''' <remarks></remarks>

Public Shared Function CheckForApplicationByName(ByVal AppName As String)

As Boolean

    Dim rtnVal As Boolean = False

    Dim p As New Process()

    For Each p In Process.GetProcesses(".")

        Try

            If p.ProcessName.ToLower() = AppName.ToLower() Then

                rtnVal = True

            End If

        Catch

            ' do nothing

        End Try

    Next

    Return rtnVal

End Function

 

Code:  Main Form (Form1.vb):

 

This form class is used to demonstrate the use of the methods exposed in the ProcessValidation.vb class. The form class is pretty simple and the annotation describes the purpose of each part of the class.

 

Public Class Form1

''' <summary>

''' List all running processes and their IDs

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub btnListAll_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnListAll.Click

 

    ' clear the textbox of any content

    txtAllProcesses.Text = String.Empty

 

    ' populate it with a list of all running processes

    ' with name and process ID shown

    txtAllProcesses.Text = ProcessValidation.ListAllProcesses()

 

End Sub

 

''' <summary>

''' Display a list of all running visible applications

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub btnListAllApps_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnListAllApps.Click

 

    ' clear the textbox of any content

    txtAllProcesses.Text = String.Empty

 

    ' populate it with a list of all running processes

    ' with name and process ID shown

    txtAllProcesses.Text = ProcessValidation.ListAllApplications()

 

End Sub

 

''' <summary>

''' Display a list of all running processes by image name

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub btnListImages_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btnListImages.Click

 

    ' clear the textbox of any content

    txtAllProcesses.Text = String.Empty

 

    ' populate it with a list of all running processes

    ' with name and process ID shown

    txtAllProcesses.Text = ProcessValidation.ListAllByImageName()

 

End Sub

 

''' <summary>

''' Look for a running process by name

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub btnSearch_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnSearch.Click

 

Dim bTest As Boolean = _ProcessValidation.CheckForProcessByName

(txtSearchProcess.Text.ToString())

 

    Select Case (bTest)

        Case True

            MessageBox.Show(txtSearchProcess.Text + " process name found.")

        Case False

            MessageBox.Show(txtSearchProcess.Text + " process name not found.")

        Case Else

            ' do nothing

    End Select

End Sub

 

''' <summary>

''' Look for a running process by image name

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub btnSearchImgname_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnSearchImgname.Click

 

    Dim bTest As Boolean = _ProcessValidation.CheckForProcessByImageName

(txtImageName.Text.ToString())

 

    Select Case (bTest)

        Case True

            MessageBox.Show(txtImageName.Text + " process name found.")

        Case False

            MessageBox.Show(txtImageName.Text + " process name not found.")

        Case Else

            ' do nothing

    End Select

 

    End Sub

 

''' <summary>

''' Find an application by name

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub btnFindApp_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnFindApp.Click

 

    Dim bTest As Boolean = _ProcessValidation.CheckForApplicationByName

  (txtApplicationName.Text.ToString())

 

        Select Case (bTest)

            Case True

                MessageBox.Show(txtApplicationName.Text + " process name found.")

            Case False

                MessageBox.Show(txtApplicationName.Text + " process name not found.")

            Case Else

            ' do nothing

        End Select

    End Sub

End Class

 

Summary:

 

This article was intended to demonstrate a simple approach to obtaining information about the processes running on a machine. The methods contained in the demonstration application show several approaches for how to list out information regarding running processes as well as how to search for a specific process.

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# Corner (http://www.c-sharpcorner.com/).


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
lv by watches On July 11, 2010
louis vuitton sold people a feeling, an image: the fashion queen, rather than a handbag. In the bag industry all over the world, many bags were short-lived, this being fashion and fashion being, by definition, epemeral. But louis vuitton bag is an exception. lv is incredible how much popularity they have gained and the reason behind this success is the high quality of Louis vuitton bags products and the iconoclastic designs.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.