回答編集履歴

3

2020/03/19 00:41

投稿

KOZ6.0
KOZ6.0

スコア2626

test CHANGED
@@ -78,8 +78,6 @@
78
78
 
79
79
  If OpenProcessToken(process.Handle, TOKEN_QUERY, tokenHandle) Then
80
80
 
81
- CloseHandle(tokenHandle)
82
-
83
81
  Return New WindowsIdentity(tokenHandle)
84
82
 
85
83
  End If

2

handle Close 漏れ

2020/03/19 00:41

投稿

KOZ6.0
KOZ6.0

スコア2626

test CHANGED
@@ -72,21 +72,27 @@
72
72
 
73
73
  Public Function GetWindowsIdentity(ByVal process As Process) As WindowsIdentity
74
74
 
75
+ Dim tokenHandle As IntPtr
76
+
75
77
  Try
76
-
77
- Dim tokenHandle As IntPtr
78
78
 
79
79
  If OpenProcessToken(process.Handle, TOKEN_QUERY, tokenHandle) Then
80
80
 
81
+ CloseHandle(tokenHandle)
82
+
81
83
  Return New WindowsIdentity(tokenHandle)
82
-
83
- CloseHandle(tokenHandle)
84
84
 
85
85
  End If
86
86
 
87
87
  Catch ex As Exception
88
88
 
89
+ Finally
89
90
 
91
+ If tokenHandle <> IntPtr.Zero Then
92
+
93
+ CloseHandle(tokenHandle)
94
+
95
+ End If
90
96
 
91
97
  End Try
92
98
 

1

WindowsIdentity を使った方法を追加

2020/03/19 00:39

投稿

KOZ6.0
KOZ6.0

スコア2626

test CHANGED
@@ -31,3 +31,93 @@
31
31
  WMI はちょっと遅いので API でゴリゴリ書いた例を紹介しておきます。(C#)
32
32
 
33
33
  [http://kozhouse.homeip.net/dotnet/etc/10/](http://kozhouse.homeip.net/dotnet/etc/10/)
34
+
35
+
36
+
37
+ ###追記
38
+
39
+ Framework に何か部品がないかなーと調べてみたのですが、System.Security.Principal.WindowsIdentity を使うと、もっと簡単になります。
40
+
41
+
42
+
43
+ ```VB.NET
44
+
45
+ Imports System.Runtime.InteropServices
46
+
47
+ Imports System.Security.Principal
48
+
49
+
50
+
51
+ Module Module1
52
+
53
+
54
+
55
+ Sub Main()
56
+
57
+ For Each p In Process.GetProcesses()
58
+
59
+ Using wid As WindowsIdentity = GetWindowsIdentity(p)
60
+
61
+ Debug.WriteLine("{0} {1}", p.ProcessName, If(wid Is Nothing, "(Error)", wid.Name))
62
+
63
+ End Using
64
+
65
+ p.Dispose()
66
+
67
+ Next
68
+
69
+ End Sub
70
+
71
+
72
+
73
+ Public Function GetWindowsIdentity(ByVal process As Process) As WindowsIdentity
74
+
75
+ Try
76
+
77
+ Dim tokenHandle As IntPtr
78
+
79
+ If OpenProcessToken(process.Handle, TOKEN_QUERY, tokenHandle) Then
80
+
81
+ Return New WindowsIdentity(tokenHandle)
82
+
83
+ CloseHandle(tokenHandle)
84
+
85
+ End If
86
+
87
+ Catch ex As Exception
88
+
89
+
90
+
91
+ End Try
92
+
93
+ Return Nothing
94
+
95
+ End Function
96
+
97
+
98
+
99
+ Private Const TOKEN_QUERY = &H8
100
+
101
+
102
+
103
+ <DllImport("advapi32.dll", SetLastError:=True)>
104
+
105
+ Private Function OpenProcessToken(ByVal ProcessHandle As IntPtr, ByVal DesiredAccess As Integer, ByRef TokenHandle As IntPtr) As Boolean
106
+
107
+ End Function
108
+
109
+
110
+
111
+ <DllImport("kernel32.dll", SetLastError:=True)>
112
+
113
+ Private Function CloseHandle(ByVal hHandle As IntPtr) As Boolean
114
+
115
+ End Function
116
+
117
+
118
+
119
+ End Module
120
+
121
+ ```
122
+
123
+ OpenProcessToken を公開しているメソッドがあれば、API 使わなくて済むのですが、今のところ見つからないです。