-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNativeMethods.cs
More file actions
56 lines (45 loc) · 1.69 KB
/
NativeMethods.cs
File metadata and controls
56 lines (45 loc) · 1.69 KB
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
55
56
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security;
namespace SingleInstanceApp
{
[SuppressUnmanagedCodeSecurity]
internal static class NativeMethods
{
/// <summary>
/// Delegate declaration that matches WndProc signatures.
/// </summary>
public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled);
[DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)]
private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs);
[DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)]
private static extern IntPtr _LocalFree(IntPtr hMem);
public static string[] CommandLineToArgvW(string cmdLine)
{
IntPtr argv = IntPtr.Zero;
try
{
int numArgs = 0;
argv = _CommandLineToArgvW(cmdLine, out numArgs);
if (argv == IntPtr.Zero)
{
throw new Win32Exception();
}
var result = new string[numArgs];
for (int i = 0; i < numArgs; i++)
{
IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr)));
result[i] = Marshal.PtrToStringUni(currArg);
}
return result;
}
finally
{
IntPtr p = _LocalFree(argv);
// Otherwise LocalFree failed.
// Assert.AreEqual(IntPtr.Zero, p);
}
}
}
}