C#視窗最小化
在C#中,你可以通過調用Form.WindowState
屬性的Minimize
方法來最小化一個視窗。以下是一個簡單的示例:
using System;
using System.Windows.Forms;
namespace WindowMinimizeExample
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MinimizeButton_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
}
}
在上面的代碼中,MinimizeButton_Click
事件處理程式被用來回響按鈕的點擊事件,它將視窗狀態設定為最小化。
你也可以通過編寫一個簡單的命令行程式來最小化一個指定的視窗,例如:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace WindowMinimizeExample
{
class Program
{
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_MINIMIZE = 6;
[STAThread]
static void Main()
{
// 假設你想要最小化一個名為 "Notepad" 的視窗
Process notepad = Process.GetProcessesByName("Notepad")[0];
ShowWindow(notepad.MainWindowHandle, SW_MINIMIZE);
}
}
}
在這個例子中,我們使用Process
類來獲取名為 "Notepad" 的進程,然後調用ShowWindow
函式來最小化它。ShowWindow
函式是Windows API的一部分,我們需要使用DllImport
屬性來調用它。
請注意,在實際的Windows應用程式中,你可能需要處理更多的邊緣情況,例如處理視窗不是活動狀態或者視窗已經被關閉的情況。