用戶打開軟件後首先看到的就是窗體和窗體上的控件,如何設置窗體的大小及合理地設置窗體和控件的關系就變得十分重要。
041 獲取桌面大小
C# 中提供了 Screen 對象,在該對象中封裝了屏幕相關信息。可以通過讀取 Screen 對象的相關屬性來獲取屏幕的信息,Screen.PrimaryScreen.WorkingArea 屬性用於獲取顯示器的工作區。工作區是顯示器的桌面區域,不包括任務欄、停靠窗口和停靠工具欄。Screen.PrimaryScreen.WorkingArea.Width 用於讀取桌面寬度;Screen.PrimaryScreen.WorkingArea.Height 可以讀取桌面的高度。

創建一個項目,默認窗體為 Form1,為 Form1 添加一個 Button 控件,用來獲取桌面大小;添加兩個 TextBox 控件,用來輸出所獲取的桌面大小。
namespace _041_DeskSize
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = Screen.PrimaryScreen.WorkingArea.Width.ToString(); //顯示桌面的寬度
textBox2.Text = Screen.PrimaryScreen.WorkingArea.Height.ToString(); //顯示桌面的高度
}
}
}
042 在窗體間移動按鈕
可視控件包含一個 Parent 屬性,該屬性表示控件的父對象。一般將此屬性設置為一個窗體,通過該屬性可以控制所屬窗體。

創建一個項目,默認窗體為 Form1,為 Form1 添加一個 Button 控件,再添加一個窗體,默認窗體的 Name 屬性為 Form2。
namespace _042_MoveButton
{
public partial class Form1 : Form
{
Form2 f;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
f = new Form2(); //實例化一個Form2對象
f.Show(); //顯示Form2窗體
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Parent == this) //當控件button1的父容器為窗體Form1時
{
f.Controls.Add(this.button1);
this.button1.Text = "返回原地";
}
else //當控件button1的父容器為窗體Form2時
{
this.Controls.Add(button1);
this.button1.Text = "開始移動";
}
}
}
043 實現 Office 助手
要實現 Office 助手效果,需要使用 Microsoft 公司提供的第三方控件。在工具箱中單擊“選擇項”,從彈出的對話框中選擇 COM 組件選項卡中的 Microsoft Agent Control 組件並加入工具箱中,然後再添加到窗體中即可。
創建一個項目,默認窗體為 Form1,為 Form1 添加一個 ListBox 控件用來讓用戶選擇人物的動作。
namespace _043_OfficeAssistant
{
public partial class Form1 : Form
{
public partial class Form1 : Form
{
IAgentCtlCharacterEx ICCE; //定義一個IAgentCtlCharacterEx類的對象
IAgentCtlRequest ICR; //定義一個IAgentCtlRequest類的對象
string[] ws = new string[10] { "Acknowledge", "LookDown", "Sad", "Alert", "LookDownBlink", "Search", "Announce", "LookUp", "Think", "Blink"}; //定義一個字符串數組
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++) //循環遍歷
{
listBox1.Items.Add(ws[i]); //向控件listBox1中添加字符串數組中的內容
}
ICR = axAgent1.Characters.Load("merlin", "merlin.acs"); //加載指定文件
ICCE = axAgent1.Characters.Character("merlin"); //設定模擬Office助手的表情
ICCE.Show(0); //顯示模擬Office助手的表情
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ICCE.StopAll(""); //停止所有模擬Office助手的表情
ICCE.Play(ws[listBox1.SelectedIndex]); //嚇死你控件listBox1中選定的表情
}
}
}