c# 윈도우 전역으로 단축키가 실행되게 한는 프로그램입니다.
최소화가 되어있어도 이 프로그램이 시작할때 단축키를 등록하기 때문에 단축키가 실행이 됩니다.
dllimport로 user32.dll에 접근해서 단축키를 등록합니다.
현재 단축키는 ctrl+q로 했습니다.
ctrl+q를 누르면 버튼을 누르게 했습니다. 이버튼을 누르게 되면 메시지 박스 를 띄우는 형식입니다.
modifier && Keys.Q 에서 modifier은 KeyInform 배열 선언한곳에서 선택하지 않았을때, 알트, 컨트롤, 쉬프트, 윈도우키를 선택할 수 있습니다.
Keys.Q 는 q를 눌렀을때 입니다.
코드입니다.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
RegisterHotKey(this.Handle, KEYid, KeyInform.Control, Keys.Q); //단축키 추가
}
//단축키
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr itp, int id, KeyInform fsInform, Keys vk);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr itp, int id);
const int KEYid = 31197;
public enum KeyInform
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
const int HOTKEYGap = 0x0312;
protected override void WndProc(ref Message message)
{
switch (message.Msg)
{
case HOTKEYGap:
Keys key = (Keys)(((int)message.LParam >> 16) & 0xFFFF); //눌러 진 단축키의 키
KeyInform modifier = (KeyInform)((int)message.LParam & 0xFFFF);//눌려진 단축키의 수식어
if ((KeyInform.Control) == modifier && Keys.Q == key)
{
this.button1.PerformClick();
}
break;
}
base.WndProc(ref message);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("실행되었습니다.");
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
UnregisterHotKey(this.Handle, KEYid);//단축키 제거
}
}
}
댓글