3

Using .Net Framework, it can be achieved here: How to get the current ProcessID?.

But how to get current PorcessId in UWP? System.Diagnostics does not even have Process class.

Community
  • 1
  • 1
kurakura88
  • 2,185
  • 2
  • 12
  • 18

2 Answers2

6
using Windows.System.Diagnostics;
var processId = ProcessDiagnosticInfo.GetForCurrentProcess().ProcessId;
Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • What assembly needs to be referenced for this `Windows.System.Diagnostics` to be available? – Jesse Chisholm Jan 18 '17 at 20:26
  • 1
    @JesseChisholm the DLL is System.Diagnostics if i'm not mistaken, it's enabled by default in all Visual Studios i've used, (2005+) – SomeNickName Jan 21 '17 at 17:00
  • The `Windows` namespace is part of UWP. You should have a reference to it automatically in any UWP project. – Raymond Chen Jan 21 '17 at 19:07
  • Get exception of "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." duration the call of GetForCurrentProcess() (vs 2017 uwp target version Build 17763) I am try to call windows32 api GetCurrentProcessId() from c#. – bronze man Jun 01 '19 at 06:30
0

As UWP allow win32 api GetCurrentProcessId, you can call it from c#. I used to call it from c++/winrt uwp project.

using System.Runtime.InteropServices;
class public xxx{
        [DllImport("Kernel32.dll", EntryPoint = "GetCurrentProcessId")]
        static extern UInt32 GetCurrentProcessId();

   public void xxx(){
            var processId = GetCurrentProcessId();
            Debug.WriteLine("my process Id:"+ processId.ToString());
   }
}

Ps1:

Windows.System.Diagnostics.ProcessDiagnosticInfo.GetForCurrentProcess() crash sometimes in my uwp c# project(not always crash). Get exception of "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Ps2:

System.Diagnostics.Process.GetCurrentProcess() not exist in my uwp c# project . https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getcurrentprocess?view=netframework-4.8

bronze man
  • 1,470
  • 2
  • 15
  • 28