iT邦幫忙

DAY 14
5

看範例學C#系列 第 14

看範例學C#-14 偵測組合鍵

可能有時候程式要做一些管理功能給維修人員使用
就可以使用組合鍵的方式,當我們按 那幾個鍵才會跑出管理功能的登入畫面出來
一般人要不小心按出來,也不太容易,按出來他也要知道帳密 才有辦法登入
這個範例我是把偵測組合鍵 寫在KeyDown事件內
這樣只要按了Ctrl + Alt + T,就會秀訊息出來
if (e.Control == true && e.Alt == true && e.KeyCode == Keys.T)//按住組合鍵 Ctrl + Alt + T
{
MessageBox.Show("Ctrl + Alt + T");
}
我還有判斷按esc就關閉程式,因為我在FormClosing也有寫確認關閉的提示
所以要按"是"才關閉程式
以下為完整程式碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ex14
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)//按下ESC
            {
                Application.Exit();//關閉程式
            }
            else
            {
                if (e.Control == true && e.Alt == true && e.KeyCode == Keys.T)//按住組合鍵 Ctrl + Alt + T
                {
                    MessageBox.Show("Ctrl + Alt + T");
                }
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //關閉程式前 確認視窗
            DialogResult Result = MessageBox.Show("尚未儲存確定要關閉程式?", "關閉確認", MessageBoxButtons.YesNo);
            if (Result == System.Windows.Forms.DialogResult.Yes)
            {
                // 關閉Form 
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}

全系列文章列表


上一篇
看範例學C#-13 防止執行檔被單獨執行
下一篇
看範例學C#-15 建立關於視窗
系列文
看範例學C#30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言