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

C# 呼叫 WinAPI 控制工作列顯示/隱藏:FindWindow 與 ShowWindow 實作

     編輯:關於C#

核心 API

APIDLL用途
FindWindowuser32.dll依類別名/視窗標題尋找視窗控制代碼
ShowWindowuser32.dll設定視窗顯示狀態

常用常數

private const int SW_HIDE = 0;      // 隱藏
private const int SW_SHOW = 5;      // 以目前大小/位置顯示
private const int SW_MINIMIZE = 6;  // 最小化
private const int SW_MAXIMIZE = 3;  // 最大化
private const int SW_RESTORE = 9;   // 還原

完整 WinForm 實作

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public partial class TaskbarControlForm : Form
{
    // P/Invoke 宣告
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    // 工作列類別名(Windows 固定)
    private const string TASKBAR_CLASS = "Shell_TrayWnd";

    public TaskbarControlForm()
    {
        InitializeComponent();
    }

    private void btnShow_Click(object sender, EventArgs e)
    {
        IntPtr hWnd = FindWindow(TASKBAR_CLASS, null);
        if (hWnd != IntPtr.Zero)
            ShowWindow(hWnd, SW_SHOW);
        else
            MessageBox.Show("找不到工作列視窗");
    }

    private void btnHide_Click(object sender, EventArgs e)
    {
        IntPtr hWnd = FindWindow(TASKBAR_CLASS, null);
        if (hWnd != IntPtr.Zero)
            ShowWindow(hWnd, SW_HIDE);
        else
            MessageBox.Show("找不到工作列視窗");
    }

    // 進階:切換顯示/隱藏
    private void btnToggle_Click(object sender, EventArgs e)
    {
        IntPtr hWnd = FindWindow(TASKBAR_CLASS, null);
        if (hWnd == IntPtr.Zero) return;

        // 取得目前可見狀態(需 IsWindowVisible)
        [DllImport("user32.dll")]
        static extern bool IsWindowVisible(IntPtr hWnd);

        ShowWindow(hWnd, IsWindowVisible(hWnd) ? SW_HIDE : SW_SHOW);
    }
}

注意事項與限制

項目說明
權限需在相同完整性層級執行(UAC 影響),管理員模式較穩定
多顯示器僅影響主螢幕工作列;次螢幕工作列類別名可能不同
Windows 版本差異Win 10/11 工作列架構變更,可能需改用 ApplicationDesktopToolbar 介面
使用者體驗隱藏工作列屬強制行為,建議提供明確使用者控制與還原機制
替代方案全螢幕模式:FormBorderStyle=None; WindowState=Maximized 而非隱藏系統工作列

擴充:控制「開始」按鈕

[DllImport("user32.dll")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, 
    string lpszClass, string lpszWindow);

// 開始按鈕類別名(Win7 為 "Button",Win10+ 可能不同)
IntPtr hStart = FindWindowEx(hTaskbar, IntPtr.Zero, "Button", null);
ShowWindow(hStart, SW_HIDE); // 隱藏開始按鈕

結語

透過 FindWindow("Shell_TrayWnd") + ShowWindow 可快速控制工作列可見性,但屬系統級干預,請謹慎使用、提供還原選項、並針對目標 OS 版本測試相容性。現代應用多採全螢幕/沉浸模式替代。

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