123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- using System;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Windows.Forms;
- namespace travelExport
- {
- public partial class Popover : Form
- {
- private int triangleSize = 10; // 小三角的边长
- private int triangleOffset; // 小三角的水平偏移量(相对于弹出框)
- public Popover()
- {
- // 初始化弹出框样式
- this.FormBorderStyle = FormBorderStyle.None; // 无边框
- this.StartPosition = FormStartPosition.Manual; // 手动设置位置
- this.BackColor = Color.White; // 背景颜色
- this.Padding = new Padding(10); // 内边距
- this.ShowInTaskbar = false; // 不在任务栏显示
- this.Opacity = 0.95; // 设置透明度
- this.Size = new Size(300, 150); // 默认大小
- // 圆角边框设置
- this.Load += (s, e) => ApplyRoundedCorners();
- // 当弹出框失去焦点时关闭
- this.Deactivate += (s, e) => this.Close();
- // 添加内容
- Label label = new Label
- {
- Text = "这是一个带指向箭头的圆角弹出框",
- AutoSize = true,
- Dock = DockStyle.Top
- };
- Button button = new Button
- {
- Text = "确认",
- Dock = DockStyle.Bottom
- };
- button.Click += (s, e) => this.Close(); // 点击关闭弹出框
- this.Controls.Add(button);
- //this.Controls.Add(label);
- }
- // 圆角和三角指向处理
- private void ApplyRoundedCorners()
- {
- int cornerRadius = 20; // 圆角半径
- var path = new GraphicsPath();
- // 绘制上方圆角矩形
- path.AddArc(0, triangleSize, cornerRadius, cornerRadius, 180, 90);
- path.AddArc(this.Width - cornerRadius, triangleSize, cornerRadius, cornerRadius, 270, 90);
- path.AddArc(this.Width - cornerRadius, this.Height - cornerRadius, cornerRadius, cornerRadius, 0, 90);
- path.AddArc(0, this.Height - cornerRadius, cornerRadius, cornerRadius, 90, 90);
- path.CloseFigure();
- // 绘制小三角
- var triangle = new PointF[]
- {
- new PointF(triangleOffset - triangleSize / 2, triangleSize),
- new PointF(triangleOffset + triangleSize / 2, triangleSize),
- new PointF(triangleOffset, 0)
- };
- path.AddPolygon(triangle);
- this.Region = new Region(path);
- }
- // 根据目标控件的位置调整弹出框的位置
- public void AdjustPosition(Control target, int margin = 10)
- {
- var screenBounds = Screen.FromControl(target).WorkingArea;
- var targetBounds = target.RectangleToScreen(target.ClientRectangle);
- // 默认弹出框显示在控件下方
- var x = targetBounds.Left;
- var y = targetBounds.Bottom + margin;
- // 如果弹出框超出屏幕右侧,调整到控件右侧
- if (x + this.Width > screenBounds.Right)
- {
- x = screenBounds.Right - this.Width - margin;
- }
- // 如果弹出框超出屏幕下方,调整到控件上方
- if (y + this.Height > screenBounds.Bottom)
- {
- y = targetBounds.Top - this.Height - margin;
- }
- // 确保弹出框不会超出屏幕左侧或顶部
- x = Math.Max(x, screenBounds.Left + margin);
- y = Math.Max(y, screenBounds.Top + margin);
- this.Location = new Point(x, y);
- // 计算小三角的水平偏移量
- triangleOffset = targetBounds.Left + targetBounds.Width / 2 - x;
- }
- }
- }
|