Search code examples
vb.netprocesspid

How to find the PID of a open program


I am trying to figure out how to find the PID, of for example notepad.exe. I have googled this, and I found lots of stuff, but I can't quite unterstand it. I've tried this code:

Dim currentProcess As Process = Process.GetCurrentProcess()
Dim localAll As Process() = Process.GetProcesses()
Dim localByName As Process() = Process.GetProcessesByName("notepad")
Label1.Text = localByName.ToString 

But when executed, I get system.diagnostics.process[] as output in label1. I am quite noob in vb.net still, and can't seem to find the problem here.


Solution

  • GetProcessesByName returns an array. You may have multiple Notepads running, but here is how you'd get the id of the first.

    Dim currentProcess As Process = Process.GetCurrentProcess()
    Dim localAll As Process() = Process.GetProcesses()
    Dim localByName As Process() = Process.GetProcessesByName("notepad")
    
    'Do this
    Label1.Text = localByName(0).Id
    

    or

    'Find all!
    for each proc in localByName
       Label1.Text &= proc.Id & vbCrLf 'vbCrlf just adds a new line for reading purposes
    next