Tạo Phím Nóng Global Cho Chương Trình
Các mã ví dụ dưới đây bao gồm:
- Class Định nghĩa các phím tắt cơ bản và nhiệm vụ của các tổ hợp phím
- Class đăng ký các phím tắt này trong register
- Tùy biến phím tắt do người dùng
- Các hàm kiểm tra điều kiện nhập khác...
Ví dụ được demo với WPF, bạn hoan toàn có thể dùng nó với Winform vì đây là các mã C# cơ bản không sử dụng thư viện đặc trưng của công nghệ WPF/WinForm.
Mã nguồn được tham khảo tại đây: MSDN Forum
using System.Windows.Forms; namespace Project1 { //This class is not required but makes managing the modifiers easier. public static class Constants { public const int NOMOD = 0x0000; public const int ALT = 0x0001; public const int CTRL = 0x0002; public const int SHIFT = 0x0004; public const int WIN = 0x0008; public const int WM_HOTKEY_MSG_ID = 0x0312; } public sealed class HotkeyManager : NativeWindow, IDisposable { public HotkeyManager() { CreateHandle(new CreateParams()); } protected override void WndProc(ref Message m) { if (m.Msg == Constants.WM_HOTKEY_MSG_ID) { if (m.WParam.ToInt32() == 123) { MessageBox.Show("HotKey ID: 123 has been pressed"); } if (m.WParam.ToInt32() == 234) { MessageBox.Show("HotKey ID: 234 has been pressed"); } } base.WndProc(ref m); } public void Dispose() { DestroyHandle(); } } }
using System.Runtime.InteropServices; namespace Project1 { public partial class Form1: Form { [DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr hWnd,int id,int fsModifiers,int vlc); [DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr hWnd, int id); public Form1() { InitializeComponent(); var HotKeyManager = new HotkeyManager(); //RegisterHotKey (Hangle, Hotkey Identifier, Modifiers, Key) RegisterHotKey(HotKeyManager.Handle, 123, Constants.ALT+ Constants.SHIFT, (int)Keys.P); RegisterHotKey(HotKeyManager.Handle, 234, Constants.ALT+ Constants.SHIFT, (int)Keys.O); } }
Áp dụng mã nguồn trên vào project của bạn để có demo như sau:
Để lưu giữ cài đặt trong demo này, ta dùng file Settings có sẵn trong project.
Properties -> Settinsg.setting
Với ví dụ này, các phím tắt có thể được gọi ở bên ngoài Form, giống như một số chương trình: Unikey, File Explorer . . .
Không có nhận xét nào:
Đăng nhận xét