1.需要匯入System.Runtime.InteropServices命名空間
2.宣告 ShowWindowAsync 函數
[DllImport("user32.dll")]
PRivatestaticexternboolShowWindowAsync(
IntPtrhWnd,
intnCmdShow
);
3.宣告 ShowWindow函數
[DllImport("user32.dll")]
publicstaticexternintShowWindow(
inthwnd,
intnCmdShow
);
4.宣告API常數定義
//API 常數定義
privateconstintSW_HIDE = 0;
privateconstintSW_NORMAL = 1;
privateconstintSW_MAXIMIZE = 3;
privateconstintSW_SHOWNOACTIVATE = 4;
privateconstintSW_SHOW = 5;
privateconstintSW_MINIMIZE = 6;
privateconstintSW_RESTORE = 9;
privateconstintSW_SHOWDEFAULT = 10;
5.上述函數功能相同,都是用來設定視窗大小,不同的是宣告的型態不一樣需轉型。
ShowWindowAsync(this.Handle, SW_MINIMIZE);
ShowWindow((int)this.Handle, SW_MINIMIZE);
6.若是把int改成IntPtr,使用ShowWindow就不用轉型,所以在宣告時就可以考慮資料型態,必免轉型所耗的資源。
[DllImport("user32.dll")]
publicstaticexternintShowWindow(
inthwnd,
intnCmdShow
);
C#完整範例
usingSystem;
usingSystem.Windows.Forms;
usingSystem.Runtime.InteropServices;
namespaceCS_WindowsResize
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
}
//API 常數定義
privateconstintSW_HIDE = 0;
privateconstintSW_NORMAL = 1;
privateconstintSW_MAXIMIZE = 3;
privateconstintSW_SHOWNOACTIVATE = 4;
privateconstintSW_SHOW = 5;
privateconstintSW_MINIMIZE = 6;
privateconstintSW_RESTORE = 9;
privateconstintSW_SHOWDEFAULT = 10;
[DllImport("user32.dll")]
privatestaticexternboolShowWindowAsync(
IntPtrhWnd,
intnCmdShow
);
[DllImport("user32.dll")]
publicstaticexternintShowWindow(
inthwnd,
intnCmdShow
);
privatevoidbutton1_Click(objectsender,EventArgse)
{
//最小化
ShowWindowAsync(this.Handle, SW_MINIMIZE);
}
privatevoidbutton2_Click(objectsender,EventArgse)
{
//最大化
ShowWindowAsync(this.Handle, SW_MAXIMIZE);
}
privatevoidbutton3_Click(objectsender,EventArgse)
{
//還原
ShowWindowAsync(this.Handle, SW_RESTORE);
}
privatevoidbutton4_Click(objectsender,EventArgse)
{
//最小化
ShowWindow((int)this.Handle, SW_MINIMIZE);
}
privatevoidbutton5_Click(objectsender,EventArgse)
{
//最大化
ShowWindow((int)this.Handle, SW_MAXIMIZE);
}
privatevoidbutton6_Click(objectsender,EventArgse)
{
//還原
ShowWindow((int)this.Handle, SW_RESTORE);
}
}
}
转载自:http://www.dotblogs.com.tw/yc421206/archive/2009/07/06/9140.aspx
新闻热点
疑难解答