做练习的时候,遇到一些问题,记录到这里,以便给和我遇到相同问题的朋友解惑和自己日后复习用
文章这里做一个字体编辑、列表控件的使用示例,让txtEdit中文本可以随着字体、字号的变化而变化,同时下同另附复制、粘贴、剪切、撤销等4个按钮。
环境:Win7 + VS2013
代码在我的资源分享中:http://download.youkuaiyun.com/detail/crazygc/8848589
一些注意点:
1) txtEdit(对应工具箱--公共控件中的TextBox)属性要设置成Multiline
2) lstFontSize(对应工具箱--公共控件中的ListBox)要手动添加一些项值。
代码部分:
1)Form1的构造函数添加3行
public Form1()
{
InitializeComponent();
GetFontFamilies(); // 用来获取系统的字体
lstFontSize.SelectedIndex = 0; // 设置字体默认值
cbxFont.SelectedIndex = 0; // 设置字号默认值
}
private void GetFontFamilies()
{
Graphics g = CreateGraphics();
FontFamily[] ffs = FontFamily.GetFamilies(g);
//sFontFamilisName=new string[ffs.Length];
cbxFont.Items.Add("华文行楷");
cbxFont.Items.Add("微软雅黑");
cbxFont.Items.Add("宋体");
/*
// 书中例子这样写的,但是实际中会抛出一个某字体不支持regular的异常
// 解决办法是:删除掉系统中会抛出异常的字体,或者手动只添加几个字体
for(int i=0;i<ffs.Length;i++)
{
sFontFamilisName[i] = ffs[i].Name;
cbxFont.Items.Add(ffs[i].Name);
}
* */
}
2) 字体变化时,事件函数
private void cbxFont_SelectedIndexChanged(object sender, EventArgs e)
{
float fFontSize;
if(lstFontSize.SelectedIndex==-1)
{
fFontSize = float.Parse(lstFontSize.Items[1].ToString());
}
else
{
fFontSize=float.Parse(lstFontSize.SelectedItem.ToString());
}
txtEdit.Font = new Font(cbxFont.Text, fFontSize);
}
3) 字号变化时,事件函数
private void lstFontSize_SelectedIndexChanged(object sender, EventArgs e)
{
string sFontName;
if(cbxFont.SelectedIndex==-1)
{
sFontName = cbxFont.Items[1].ToString();
}
else
{
sFontName = cbxFont.Text;
}
txtEdit.Font = new Font(sFontName, float.Parse(lstFontSize.SelectedItem.ToString()));
}
4) 复制处理
private void btnCopy_Click(object sender, EventArgs e)
{
if(txtEdit.SelectionLength>0)
{
txtEdit.Copy();
}
}
5) 粘贴处理
private void btnPaste_Click(object sender, EventArgs e)
{
txtEdit.Paste();
}
6) 剪切处理
private void btnCut_Click(object sender, EventArgs e)
{
txtEdit.Cut();
}
7) 撤销处理
private void btnUndo_Click(object sender, EventArgs e)
{
// 如果只写txtEdit.Undo();则会在上一次和本次状态之间来回切换
// 这样写只能撤销到上一个状态,而且不能回退
if(txtEdit.CanUndo==true)
{
txtEdit.Undo();
txtEdit.ClearUndo();
}
}
8) 一些演示