程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> Visual C#彈出窗口殺手(4)

Visual C#彈出窗口殺手(4)

編輯:關於C語言

代碼下載:

演示程序:

注冊系統熱鍵

系統熱鍵用在像彈出窗口殺手這種應用程序非常有用, Ctrl+Shift+J是缺省熱鍵。

說道實現,我們繼續用RegisterHotkey(HWND hWnd, int id, UINT fsModifIErs, UINT vkey)。完成,代碼如下:

public void SetHotKey(Keys c, bool bCtrl, bool bShift, bool bAlt, bool bWindows)
{
m_hotkey = c;
m_ctrlhotkey = bCtrl;
m_shifthotkey = bShift;
m_althotkey = bAlt;
m_winhotkey = bWindows;
// update hotkey
NativeWIN32.KeyModifiers modifiers = NativeWIN32.KeyModifIErs.None;
if (m_ctrlhotkey)
modifiers |= NativeWIN32.KeyModifIErs.Control;
if (m_shifthotkey)
modifiers |= NativeWIN32.KeyModifIErs.Shift;
if (m_althotkey)
modifiers |= NativeWIN32.KeyModifIErs.Alt;
if (m_winhotkey)
modifiers |= NativeWIN32.KeyModifIErs.Windows;
NativeWIN32.RegisterHotKey(Handle, 100, modifIErs, m_hotkey); //Keys.J);
}
一般的,注冊熱鍵要一下幾步
/* ------- using HOTKEYs in a C# application -------
-- code snippet by James J Thompson --
在Form的load 中 : Ctrl+Shift+J
bool success = RegisterHotKey(Handle,
100,
KeyModifiers.Control | KeyModifIErs.Shift,
Keys.J);

在 form的closing中 :

UnregisterHotKey(Handle, 100);

如何處理熱鍵 :

protected override void WndProc( ref Message m )
{
const int WM_HOTKEY = 0x0312;
switch(m.Msg)
{
case WM_HOTKEY:
MessageBox.Show("Hotkey pressed");
ProcessHotkey();
break;
}
base.WndProc(ref m );
}
public class NativeWIN32
{
[DllImport("user32.dll", SetLastError=true)]
public static extern bool RegisterHotKey( IntPtr hWnd, // handle to window
int id, // hot key identifIEr
KeyModifiers fsModifiers, // key-modifIEr options
Keys vk // virtual-key code
);
[DllImport("user32.dll", SetLastError=true)]
public static extern bool UnregisterHotKey( IntPtr hWnd, // handle to window
int id // hot key identifIEr
);
[Flags()]
public enum KeyModifIErs
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
}
------- using HOTKEYs in a C# application ------- */

當我們按下熱鍵以後,流程是這樣:首先用HWND GetForegroundWindow()來得到窗體,然後要抓出窗體的標題, GetWindowText(HWND hwnd, /*out*/LPTSTR lpString, int nMaxCount). 具體如下:

protected void ProcessHotkey()
{
IntPtr hwnd = NativeWIN32.GetForegroundWindow();
if (!hwnd.Equals(IntPtr.Zero))
{
NativeWIN32.STRINGBUFFER sWindowTitle;
NativeWIN32.GetWindowText(hwnd, out sWindowTitle, 256);
if (sWindowTitle.szText.Length>0)
AddWindowTitle( sWindowTitle.szText ); // add to the ListVIEw (Form)
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved