■ RmGetList API 메소드를 사용해 잠금 프로세스 찾기

------------------------------------------------------------------------------------------------------------------------


TestProject.zip


ProcessHelper.cs

 

 

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.dll", 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.dll", 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.dll", 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.dll", 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

 

 

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

    }

}

 

------------------------------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요