首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實現螢幕鍵盤 ScreenKeyboard(六)——全域滑鼠鉤子實現無焦點視窗與最終效果

     編輯:關於C語言

核心需求:不可取得焦點但可拖曳

螢幕鍵盤視窗不可搶奪輸入焦點 (否則目標應用程式失去焦點),但標題列點擊需可拖曳移動視窗。

全域滑鼠鉤子實現


UserActivityHook hook = new UserActivityHook(true, true);
hook.MouseActivity += HookOnMouseActivity;

private void HookOnMouseActivity(object sender, HookEx.MouseExEventArgs e)
{
    Point location = e.Location;
    if (e.Button == MouseButtons.Left)
    {
        Rectangle captionRect = new Rectangle(this.Location, 
            new Size(this.Width, SystemInformation.CaptionHeight));
        
        if (captionRect.Contains(location))
        {
            // 標題列點擊:移除 WS_DISABLED,允許取得焦點並置前
            NativeMethods.SetWindowLong(this.Handle, KeyboardConstaint.GWL_EXSTYLE,
                (int)NativeMethods.GetWindowLong(this.Handle, KeyboardConstaint.GWL_EXSTYLE)
                & (~KeyboardConstaint.WS_DISABLED));
            NativeMethods.SendMessage(this.Handle, KeyboardConstaint.WM_SETFOCUS, IntPtr.Zero, IntPtr.Zero);
        }
        else
        {
            // 非標題列:加上 WS_DISABLED,不可取得焦點
            NativeMethods.SetWindowLong(this.Handle, KeyboardConstaint.GWL_EXSTYLE,
                (int)NativeMethods.GetWindowLong(this.Handle, KeyboardConstaint.GWL_EXSTYLE)
                | KeyboardConstaint.WS_DISABLED);
        }
    }
}

關鍵 API 運用

  • SetWindowLong (GWL_EXSTYLE):動態切換 WS_DISABLED 樣式
  • WM_SETFOCUS:主動請求焦點 (僅標題列點擊時)
  • 全域滑鼠鉤子 (WH_MOUSE_LL):攔截系統級滑鼠事件,不受視窗焦點限制

最終執行效果

螢幕鍵盤最終效果圖

專案連結

系列總結

六部分完整涵蓋:鉤子理論 → API 封裝 → 鍵盤/滑鼠鉤子安裝 → 訊息模擬 → 按鈕 UI 綁定 → 無焦點視窗技巧。實現與實體鍵盤完全同步的虛擬鍵盤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved