[C#/COMMON] RmGetList API 함수를 사용해 잠금 프로세스 찾기
■ RmGetList API 함수를 사용해 잠금 프로세스를 찾는 방법을 보여준다. ▶ ProcessHelper.cs
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; namespace TestProject { /// <summary> /// 프로세스 헬퍼 /// </summary> public class ProcessHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Enumeration ////////////////////////////////////////////////////////////////////////////////////////// Private #region 애플리케이션 타입 - ApplicationType /// <summary> /// 애플리케이션 타입 /// </summary> private enum ApplicationType { /// <summary> /// RM_UNKNOWN_APP /// </summary> RM_UNKNOWN_APP = 0, /// <summary> /// RM_MAIN_WINDOW /// </summary> RM_MAIN_WINDOW = 1, /// <summary> /// RM_OTHER_WINDOW /// </summary> RM_OTHER_WINDOW = 2, /// <summary> /// RM_SERVICE /// </summary> RM_SERVICE = 3, /// <summary> /// RM_EXPLORER /// </summary> RM_EXPLORER = 4, /// <summary> /// RM_CONSOLE /// </summary> RM_CONSOLE = 5, /// <summary> /// RM_CRITICAL /// </summary> RM_CRITICAL = 1000 } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region 유일 프로세스 - UNIQUE_PROCESS /// <summary> /// 유일 프로세스 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct UNIQUE_PROCESS { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 프로세스 ID /// </summary> public int ProcessID; /// <summary> /// 프로세스 시작 시간 /// </summary> public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime; #endregion } #endregion #region 프로세스 정보 - PROCESS_INFORMATION /// <summary> /// 프로세스 정보 /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] private struct PROCESS_INFORMATION { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 프로세스 /// </summary> public UNIQUE_PROCESS Process; /// <summary> /// 애플리케이션명 /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)] public string ApplicationName; /// <summary> /// 서비스 단축명 /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)] public string ServiceShortName; /// <summary> /// 애플리케이션 타입 /// </summary> public ApplicationType ApplicationType; /// <summary> /// 애플리케이션 상태 /// </summary> public uint ApplicationStatus; /// <summary> /// TS 세션 ID /// </summary> public uint TSSessionID; /// <summary> /// 재시작 여부 /// </summary> [MarshalAs(UnmanagedType.Bool)] public bool Restartable; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Delegate ////////////////////////////////////////////////////////////////////////////////////////// Private #region 트리 노드 추가하기 대리자 - AddTreeNodeDelegate(node) /// <summary> /// 트리 노드 추가하기 대리자 /// </summary> /// <param name="node">노드</param> private delegate void AddTreeNodeDelegate(TreeNode node); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 세션 시작하기 - RmStartSession(sessionHandle, sessionFlag, sessionKey) /// <summary> /// 세션 시작하기 /// </summary> /// <param name="sessionHandle">세션 핸들</param> /// <param name="sessionFlag">세션 플래그</param> /// <param name="sessionKey">세션 키</param> /// <returns>처리 결과</returns> [DllImport("rstrtmgr", CharSet = CharSet.Auto, SetLastError = true)] private static extern int RmStartSession(out uint sessionHandle, int sessionFlag, string sessionKey); #endregion #region 리소스 등록하기 - RmRegisterResources(sessionHandle, fileCount, fileNameArray, processCount, processArray, serviceCount, serviceNameArray) /// <summary> /// 리소스 등록하기 /// </summary> /// <param name="sessionHandle">세션 핸들</param> /// <param name="fileCount">파일 수</param> /// <param name="fileNameArray">파일명 배열</param> /// <param name="processCount">프로세스 수</param> /// <param name="processArray">프로세스 배열</param> /// <param name="serviceCount">서비스 수</param> /// <param name="serviceNameArray">서비스명 배열</param> /// <returns>처리 결과</returns> [DllImport("rstrtmgr", CharSet = CharSet.Auto, SetLastError = true)] private static extern int RmRegisterResources(uint sessionHandle, uint fileCount, string[] fileNameArray, uint processCount, [In] UNIQUE_PROCESS[] processArray, uint serviceCount, string[] serviceNameArray); #endregion #region 리스트 구하기 - RmGetList(sessionHandle, processCountNeeded, processCount, processArray, rebootReason) /// <summary> /// 리스트 구하기 /// </summary> /// <param name="sessionHandle">세션 핸들</param> /// <param name="receiveProcessCount">필요 프로세스 수</param> /// <param name="processCount">프로세스 수</param> /// <param name="processArray">프로세스 배열</param> /// <param name="rebootReason">재부팅 사유</param> /// <returns>처리 결과</returns> [DllImport("rstrtmgr", CharSet = CharSet.Auto, SetLastError = true)] private static extern int RmGetList(uint sessionHandle, out uint processCountNeeded, ref uint processCount, [In, Out] PROCESS_INFORMATION[] processArray, ref uint rebootReason); #endregion #region 세션 종료하기 - RmEndSession(sessionHandle) /// <summary> /// 세션 종료하기 /// </summary> /// <param name="sessionHandle">세션 핸들</param> /// <returns>처리 결과</returns> [DllImport("rstrtmgr", CharSet = CharSet.Auto, SetLastError = true)] private static extern int RmEndSession(uint sessionHandle); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// RM_REBBOT_REASON_NONE /// </summary> private const int RM_REBBOT_REASON_NONE = 0; /// <summary> /// CCH_RM_MAX_APP_NAME /// </summary> private const int CCH_RM_MAX_APP_NAME = 255; /// <summary> /// CCH_RM_MAX_SVC_NAME /// </summary> private const int CCH_RM_MAX_SVC_NAME = 63; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 잠금 프로세스 리스트 구하기 - GetLockingProcessList(filePath) /// <summary> /// 잠금 프로세스 리스트 구하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>잠금 프로세스 리스트</returns> public static List<Process> GetLockingProcessList(string filePath) { uint sessionHandle; string sessionKey = Guid.NewGuid().ToString(); int result = RmStartSession(out sessionHandle, 0, sessionKey); if(result != 0) { throw new Exception($"재시작 관리자 세션 시작시 에러가 발생했습니다 : {result}"); } List<Process> processList = new List<Process>(); try { const int ERROR_MORE_DATA = 234; string[] resourceArray = new string[] { filePath }; result = RmRegisterResources ( sessionHandle, (uint)resourceArray.Length, resourceArray, 0, null, 0, null ); if(result != 0) { throw new Exception("리소스를 등록할 수 없습니다."); } uint processCountNeeded = 0; uint processCount = 0; uint rebootReason = RM_REBBOT_REASON_NONE; result = RmGetList(sessionHandle, out processCountNeeded, ref processCount, null, ref rebootReason); if(result == ERROR_MORE_DATA) { PROCESS_INFORMATION[] processArray = new PROCESS_INFORMATION[processCountNeeded]; processCount = processCountNeeded; result = RmGetList(sessionHandle, out processCountNeeded, ref processCount, processArray, ref rebootReason); if(result != 0) { throw new Exception($"잠금 프로세스 목록 표시시 에러가 발생했습니다 : {result}"); } for(int i = 0; i < processCount; i++) { try { processList.Add(Process.GetProcessById(processArray[i].Process.ProcessID)); } catch(ArgumentException) { } } } else if(result != 0) { throw new Exception($"결과 크기 구하는 중 에러가 발생했습니다 : {result}"); } } catch(Exception exception) { MessageBox.Show(exception.Message); } finally { RmEndSession(sessionHandle); } return processList; } #endregion } } |
▶ MainForm.cs
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 95 96 97 98 99 |
using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); #region 이벤트를 설정한다. Load += Form_Load; this.filePathButton.Click += filePathButton_Click; this.findButton.Click += findButton_Click; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 폼 로드시 처리하기 - Form_Load(sender, e) /// <summary> /// 폼 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_Load(object sender, EventArgs e) { this.filePathTextBox.Text = Application.ExecutablePath; } #endregion #region 파일 경로 버튼 클릭시 처리하기 - filePathButton_Click(sender, e) /// <summary> /// 파일 경로 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void filePathButton_Click(object sender, EventArgs e) { if(this.openFileDialog.ShowDialog() == DialogResult.OK) { this.filePathTextBox.Text = this.openFileDialog.FileName; } } #endregion #region 잠금 프로세스 찾기 버튼 클릭시 처리하기 - findButton_Click(sender, e) /// <summary> /// 잠금 프로세스 찾기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void findButton_Click(object sender, EventArgs e) { try { this.listBox.Items.Clear(); List<Process> processList = ProcessHelper.GetLockingProcessList(this.filePathTextBox.Text); foreach(Process process in processList) { this.listBox.Items.Add(process.ProcessName); } } catch(Exception exception) { MessageBox.Show(exception.Message); } } #endregion } } |
TestProject.zip