核心 API
| API | DLL | 用途 |
FindWindow | user32.dll | 依類別名/視窗標題尋找視窗控制代碼 |
ShowWindow | user32.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 版本測試相容性。現代應用多採全螢幕/沉浸模式替代。