본문 바로가기
개발언어/C#

[C#/WINFORM] Control 클래스 : ProcessCmdKey 메소드를 사용해 CTRL, SHIFT, ALT 조합 키 입력받기

by 창용이랑 2023. 4. 17.
728x90

TestProject.zip
0.01MB

▶ MainForm.cs

using System.Windows.Forms;

namespace TestProject
{
    /// <summary>
    /// 메인 폼
    /// </summary>
    public partial class MainForm : Form
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainForm()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Protected

        #region 명령 키 처리하기 - ProcessCmdKey(message, keyData)

        /// <summary>
        /// 명령 키 처리하기
        /// </summary>
        /// <param name="message">메시지</param>
        /// <param name="keyData">키 데이터</param>
        /// <returns>처리 결과</returns>
        protected override bool ProcessCmdKey(ref Message message, Keys keyData)
        {
            Keys keys = keyData & ~(Keys.Shift | Keys.Control | Keys.Alt);
            
            switch(keys)
            {
                case Keys.S :

                    if((keyData & Keys.Control) != 0)
                    {
                        MessageBox.Show("CTRL + S KEY PRESSED!", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    
                    break;

                case Keys.F5 :

                    MessageBox.Show("F5 KEY PRESSED!", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    break;

                case Keys.Tab :

                    if((keyData & Keys.Shift) != 0)
                    {
                        MessageBox.Show("SHIFT + TAB KEY PRESSED!", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    
                    break;

                case Keys.Enter :

                    if((keyData & Keys.Alt) != 0)
                    {
                        MessageBox.Show("ALT + ENTER KEY PRESSED!", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    
                    break;
            }
            
            return base.ProcessCmdKey(ref message, keyData);
        }

        #endregion
    }
}

 

출처 : ICODEBROKER :: [C#/WINFORM] Control 클래스 : ProcessCmdKey 메소드를 사용해 CTRL, SHIFT, ALT 조합 키 입력받기 (tistory.com)