第二章例题:EnvironmentVars
对应教材2.2.2中的(12)部分,主要对ListBox控件进行演示
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;

public class EnvironmentVars:Form
{
Label label;

public static void Main()
{
Application.Run(new EnvironmentVars());
}
public EnvironmentVars()
{
//设置窗体属性,这些属性属于基类Form
Text = "Environment Variables";
//动态创建Label控件
label = new Label();
label.Parent = this;
label.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label.Location = new Point(Font.Height,Font.Height);
label.Size = new Size(ClientSize.Width - 2 * Font.Height,Font.Height);
//动态创建ListBox控件
ListBox listbox = new ListBox();
listbox.Parent = this;
listbox.Location = new Point(Font.Height,3 * Font.Height);
listbox.Size = new Size(12 * Font.Height,8 * Font.Height);
listbox.Sorted = true;
listbox.SelectedIndexChanged += new EventHandler(ListBoxOnSelectedIndexChanged);

//获取环境变量
IDictionary dict = Environment.GetEnvironmentVariables();
string[] astr = new string[dict.Keys.Count];

//将环境变量的键值(Key)显示到ListBox中
dict.Keys.CopyTo(astr,0);
listbox.Items.AddRange(astr);
listbox.SelectedIndex = 0;

}

void ListBoxOnSelectedIndexChanged(object obj,EventArgs ea)
{
//获取用户点击的ListBox条目及数据
ListBox listbox = (ListBox)obj;
string strItem = (string)listbox.SelectedItem;

//将对应键值的环境变量值显示到Label上
label.Text = Environment.GetEnvironmentVariable(strItem);
}
}

完整源代码下载:EnvironmentVars.rar
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
public class EnvironmentVars:Form
{
Label label;
public static void Main()
{
Application.Run(new EnvironmentVars());
}
public EnvironmentVars()
{
//设置窗体属性,这些属性属于基类Form
Text = "Environment Variables";
//动态创建Label控件
label = new Label();
label.Parent = this;
label.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label.Location = new Point(Font.Height,Font.Height);
label.Size = new Size(ClientSize.Width - 2 * Font.Height,Font.Height);
//动态创建ListBox控件
ListBox listbox = new ListBox();
listbox.Parent = this;
listbox.Location = new Point(Font.Height,3 * Font.Height);
listbox.Size = new Size(12 * Font.Height,8 * Font.Height);
listbox.Sorted = true;
listbox.SelectedIndexChanged += new EventHandler(ListBoxOnSelectedIndexChanged);
//获取环境变量
IDictionary dict = Environment.GetEnvironmentVariables();
string[] astr = new string[dict.Keys.Count];
//将环境变量的键值(Key)显示到ListBox中
dict.Keys.CopyTo(astr,0);
listbox.Items.AddRange(astr);
listbox.SelectedIndex = 0;
}
void ListBoxOnSelectedIndexChanged(object obj,EventArgs ea)
{
//获取用户点击的ListBox条目及数据
ListBox listbox = (ListBox)obj;
string strItem = (string)listbox.SelectedItem;
//将对应键值的环境变量值显示到Label上
label.Text = Environment.GetEnvironmentVariable(strItem);
}
}



浙公网安备 33010602011771号