您的位置:首页 > 编程语言 > C#

c# 使用api函数 ShowWindowAsync 控制窗体

2014-09-29 17:12 288 查看
1.需要匯入 System.Runtime.InteropServices 命名空間

2.宣告 ShowWindowAsync 函數

[DllImport("user32.dll")]

private static extern bool ShowWindowAsync(

IntPtr hWnd,

int nCmdShow

);

3.宣告 ShowWindow函數

[DllImport("user32.dll")]

public static extern int ShowWindow(

int hwnd,

int nCmdShow

);

4.宣告API常數定義

//API 常數定義

private const int SW_HIDE = 0;

private const int SW_NORMAL = 1;

private const int SW_MAXIMIZE = 3;

private const int SW_SHOWNOACTIVATE = 4;

private const int SW_SHOW = 5;

private const int SW_MINIMIZE = 6;

private const int SW_RESTORE = 9;

private const int SW_SHOWDEFAULT = 10;

5.上述函數功能相同,都是用來設定視窗大小,不同的是宣告的型態不一樣需轉型。

ShowWindowAsync(this.Handle, SW_MINIMIZE);

ShowWindow((int)this.Handle, SW_MINIMIZE);

6.若是把int 改成IntPtr ,使用ShowWindow就不用轉型,所以在宣告時就可以考慮資料型態,必免轉型所耗的資源。

[DllImport("user32.dll")]

public static extern int ShowWindow(

int hwnd,

int nCmdShow

);

C#完整範例

using System;

using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace CS_WindowsResize

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

//API 常數定義

private const int SW_HIDE = 0;

private const int SW_NORMAL = 1;

private const int SW_MAXIMIZE = 3;

private const int SW_SHOWNOACTIVATE = 4;

private const int SW_SHOW = 5;

private const int SW_MINIMIZE = 6;

private const int SW_RESTORE = 9;

private const int SW_SHOWDEFAULT = 10;

[DllImport("user32.dll")]

private static extern bool ShowWindowAsync(

IntPtr hWnd,

int nCmdShow

);

[DllImport("user32.dll")]

public static extern int ShowWindow(

int hwnd,

int nCmdShow

);

private void button1_Click(object sender, EventArgs e)

{

//最小化

ShowWindowAsync(this.Handle, SW_MINIMIZE);

}

private void button2_Click(object sender, EventArgs e)

{

//最大化

ShowWindowAsync(this.Handle, SW_MAXIMIZE);

}

private void button3_Click(object sender, EventArgs e)

{

//還原

ShowWindowAsync(this.Handle, SW_RESTORE);

}

private void button4_Click(object sender, EventArgs e)

{

//最小化

ShowWindow((int)this.Handle, SW_MINIMIZE);

}

private void button5_Click(object sender, EventArgs e)

{

//最大化

ShowWindow((int)this.Handle, SW_MAXIMIZE);

}

private void button6_Click(object sender, EventArgs e)

{

//還原

ShowWindow((int)this.Handle, SW_RESTORE);

}

}

}

转载自:http://www.dotblogs.com.tw/yc421206/archive/2009/07/06/9140.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: