ShowInfoWindow函数用来将提示窗口显示出来,该函数需要将提示窗口附着的控件和需要显示的文本传递过来。然后,AnchorPointFromControl根据控件的位置返回提示窗口的箭头应该显示的坐标,代码如下:
public static Point AnchorPointFromControl(Control anchorControl) { if (anchorControl == null) throw new ArgumentException(); Point controlLocation = anchorControl.Location; System.Drawing.Size controlSize = anchorControl.Size;
if (anchorControl.Parent != null) controlLocation = anchorControl.Parent.PointToScreen(controlLocation); return controlLocation + new Size(controlSize.Width / 2, controlSize.Height / 2); } | PointToScreen表明将工作区点的位置映射成屏幕坐标统一进行计算。上述代码最后以行说明提示窗口的箭头显示在附着控件的中点。
将提示窗口的背景颜色设置成Info,外观如下图:
我们发现这样的外观有点别扭,没错!因为提示窗口缺少黑色边框!所以,还需要在窗体的OnPaint事件中添加代码,如下:
protected override void OnPaint(PaintEventArgs e) { Pen p = new Pen(Color.Black , 2); e.Graphics.DrawPath(p, gPath); base.OnPaint(e); } |
二、程序实现
启动Visual Studio 2005,新建Visual C#的Windows 应用程序项目,并取名为ShowInfoWindow,添加4个Button组件、1个Label组件、1个textBox组件和3个Panel组件,其中3个Button用来显示标注式消息提示窗口并分别附着在三个组件之上,代码如下:
…… private InfoWindow iw; …… private void button1_Click(object sender, EventArgs e) { iw = new InfoWindow(); iw.ShowInfoWindow(label1, "关于标签组件的提示说明。"); } private void button3_Click(object sender, EventArgs e) { iw = new InfoWindow(); iw.ShowInfoWindow(button2, "关于按钮组件的提示说明。"); }
private void button4_Click(object sender, EventArgs e) { iw = new InfoWindow(); iw.ShowInfoWindow(textBox1, "关于文本框组件的提示说明。"); } | 然后,我们在项目中添加新Windows窗体,取名为InfoWindow,将InfoWindow的BackColor设为Info,FormBorderStyle设为None,将ShowIcon和ShowInTaskbar都设为False,在窗体上放置1个Label组件和1个Button组件,分别用来显示消息内容和关闭提示窗口的操作。具体实现请参见文章附带的源码,这里不再详述。
三、总结
本文演示了标注式消息提示窗口的创建和显示,利用GraphicsPath对象、Region对象以及屏幕坐标映射等方法有效的实现了提示窗口的外观和样式,提示窗口可以自动附着在相应控件之上,并且根据附着控件在屏幕上的位置自动调整提示窗口箭头的位置和大小。演示程序在Windows XP SP2以及.net 框架 2.0环境下运行通过。 上一页 [1] [2]
 【责编:Luzi】 |