~ruther/csharp-dll-injector

ref: da3477de37f81c8009d155d138a5ab42ad3fa8f4 csharp-dll-injector/DllUtils/Process/ProcessHandle.cs -rw-r--r-- 1.3 KiB
da3477de — František Boháček Add solution 5 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DllUtils.Exceptions;
using DllUtils.Interop;

namespace DllUtils.Process
{
    public class ProcessHandle
    {
        public ProcessHandle(System.Diagnostics.Process process)
        {
            Process = process;
        }

        public IntPtr Handle { get; private set; }

        public bool IsOpened { get; private set; }

        public System.Diagnostics.Process Process { get; }

        public string ProcessName => Process.ProcessName;

        public int ProcessId => Process.Id;

        public void Close()
        {
            if (Handle != IntPtr.Zero && IsOpened)
            {
                Kernel32.CloseHandle(Handle);
                Handle = IntPtr.Zero;
            }

            IsOpened = false;
        }

        public void Open()
        {
            if (!IsOpened || Handle == IntPtr.Zero)
            {
                Handle = Kernel32.OpenProcess((0x2 | 0x8 | 0x10 | 0x20 | 0x400), 1, (uint)ProcessId);

                if (Handle == IntPtr.Zero)
                {
                    throw new OpenHandleException($"Failed to open process handle for {ProcessName}");
                }
            }

            IsOpened = true;
        }
    }
}
Do not follow this link