以下是做项目时实现的二种类似于QQ表情弹出框功能的实现方法,方法一采用DataGridView实现,方法二通过ToolStripDropDown实现。
一先贴出实现效果。
方法一 DataGridView效果

方法二ToolStripDropDown效果

二 二种方法实现的对比:
方法一 效果类似于QQ,鼠标放在上面时,可以看到显示的效果,但加裁速度有些慢。
方法二的效果类似于MSN,加裁速度比较快,鼠标放在上面时能显示图片的ToolTipText。
三 实现源代码
(1) 方法一。该方法是把图片的位置值存放到DataGridVeiw各个单元格中,在DataGridView的dataGridView1_CellFormatting。这里使用到了e.Value中的Object类型。由于 e.Value为Object类型,所以可以直接显示图片。
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//如果值不为空
if(e.Value!=null)
{
string path = e.Value.ToString();//得到路径值
e.Value = GetImage(path);//根据路径值获取图片。因为e.Value是Object,图片文件可以直接显示
}
else
{
e.Value = Properties.Resources.snow;//默读背景图片
}
}
在GetImage方法中,读取图片时采用File.OpenRead(path) 方法,该方法可以防止图片文件正在被另一程序访问或只读或未释放。如果采用Image.FormFile()则可能会出现异常。
/// <summary>
/// 加裁图片
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private object GetImage(string path)
{
try
{
FileStream fs = File.OpenRead(path);//调用该方法,可以防止文件正在防问或只读或被锁定状态
int filelength = 0;
filelength = (int)fs.Length; //获得文件长度
Byte[] image = new Byte[filelength]; //建立一个字节数组
fs.Read(image, 0, filelength); //按字节流读取
System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
fs.Close();
return result;
}
catch (Exception)
{
}
return null;
}
当鼠标通过图片时用PictureBox显示图片
DataGridViewCellStyle sty = new DataGridViewCellStyle();
sty.BackColor = Color.Snow;
object path = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
cell.Style = sty;
}
}
DataGridViewCellStyle sty2 = new DataGridViewCellStyle();
sty2.BackColor = Color.Blue;
if (path != null)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = sty2;
Image img = Bitmap.FromFile(path.ToString());
if (e.RowIndex < 4 && e.ColumnIndex < 4)
{
pictureBox1.Visible = false;
pictureBox31.Visible = true;
}
else
{
pictureBox1.Visible = true;
pictureBox31.Visible = false;
}
pictureBox1.Image = img;
pictureBox31.Image = img;
}
else
{
pictureBox1.Image = Properties.Resources.snow;
pictureBox31.Image = Properties.Resources.snow;
}
以上就是方法一的主要实现过程,该方法有一个不好的地方就是速度比较慢,因为dataGridView1_CellFormatting事件发生太频繁,导致一直在加裁图片。
方法二 通过ToolStripDropDown(http://msdn.microsoft.com/zh-cn/library/system.windows.forms.toolstripdropdown_methods.aspx)实现.
ToolStripLayoutStyle 值:
Table1
2 Flow
3 StackWithOverflow
4 HorizontalStackWithOverflow
5 VerticalStackWithOverflow。
如果 LayoutStyle 属性设置为 Flow 或 Table,将不会显示大小调整手柄。
这里设置emotionDropDown.LayoutStyle = ToolStripLayoutStyle.Table;//设置布局.
代码
/// <summary>
/// 发送表情
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void emotion_Click(object sender, EventArgs e)
{
ToolStripItem item = (ToolStripItem)sender;
if(item==null)
{
return;
}
string text = item.ToolTipText;
if (text.Split(' ').Length > 1)
{
text = text.Split(' ')[1];
}
richtxtSend.AppendText(text);//发送Text
richtxtSend.Focus();
SendButton.Enabled = true;
}
以上是主要代码。RtfRichTextBox 下载