-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSessionStateService.cs
More file actions
94 lines (80 loc) · 2.71 KB
/
Copy pathSessionStateService.cs
File metadata and controls
94 lines (80 loc) · 2.71 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System.Runtime.InteropServices;
namespace BatteryDown;
internal static class SessionStateService
{
private const uint InvalidSessionId = 0xFFFFFFFF;
private const int WtsSessionInfoEx = 25;
private const int SessionLocked = 0;
private static readonly IntPtr WtsCurrentServerHandle = IntPtr.Zero;
public static bool IsLocked
{
get
{
var sessionId = WTSGetActiveConsoleSessionId();
if (sessionId == InvalidSessionId)
{
return true;
}
if (!WTSQuerySessionInformation(
WtsCurrentServerHandle,
sessionId,
WtsSessionInfoEx,
out var buffer,
out _))
{
throw new InvalidOperationException("无法读取当前 Windows 会话状态。");
}
try
{
var info = Marshal.PtrToStructure<WtsInfoEx>(buffer);
return info.Level == 1 && info.Data.SessionFlags == SessionLocked;
}
finally
{
WTSFreeMemory(buffer);
}
}
}
[DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId();
[DllImport("wtsapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool WTSQuerySessionInformation(
IntPtr serverHandle,
uint sessionId,
int infoClass,
out IntPtr buffer,
out uint bytesReturned);
[DllImport("wtsapi32.dll")]
private static extern void WTSFreeMemory(IntPtr memory);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WtsInfoEx
{
public int Level;
public WtsInfoExLevel1 Data;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WtsInfoExLevel1
{
public int SessionId;
public int SessionState;
public int SessionFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 33)]
public string WinStationName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21)]
public string UserName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 18)]
public string DomainName;
public long LogonTime;
public long ConnectTime;
public long DisconnectTime;
public long LastInputTime;
public long CurrentTime;
public int IncomingBytes;
public int OutgoingBytes;
public int IncomingFrames;
public int OutgoingFrames;
public int IncomingCompressedBytes;
public int OutgoingCompressedBytes;
}
}