思路:
使用透明无框窗体覆盖需要添加水印的窗体,并设置owner为主窗体。然后在透明窗体绘制水印文本即可
新增水印类:
public class Watermark
{
private string text;
private int gap;
private Font font = new Font("微软雅黑", 16, FontStyle.Regular);
private Color color = Color.FromArgb(255, 0, 0, 0);
private Form form = new Form();
public Watermark(Form ownerForm, string text = "水印信息", int gap = 75, double opacity = 0.1, Font font = null, Color? color = null)
{
this.text = text;
this.gap = gap;
if (font != null)
{
this.font = font;
}
if (color.HasValue)
{
this.color = color.Value;
}
form.Size = ownerForm.Size;
ownerForm.SizeChanged += OwnerForm_SizeChanged;
ownerForm.Move += OwnerForm_Move;
form.Owner = ownerForm;
form.FormBorderStyle = FormBorderStyle.None;
form.Opacity = opacity;
form.ShowInTaskbar = false;
form.TransparencyKey = Color.White;
form.BackColor = Color.White;
form.Paint += Form_Paint;
form.Show();
GetWindowLong(form.Handle, GWL_EXSTYLE);
SetWindowLong(form.Handle, GWL_EXSTYLE, WS_EX_TRANSPARENT | WS_EX_LAYERED);
}
private void OwnerForm_Move(object sender, EventArgs e)
{
form.Location = ((Form)sender).Location;
}
private void OwnerForm_SizeChanged(object sender, EventArgs e)
{
form.Size = ((Form)sender).Size;
}
private void Form_Paint(object sender, PaintEventArgs e)
{
const float cos30 = 0.866f;
const float sin30 = 0.5f;
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
//平移画布到需要画印章的位置
g.TranslateTransform(0, gap);
//逆时针旋转30度
g.RotateTransform(-30);
// 绘制画布区域
//g.FillRectangle(new SolidBrush(Color.FromArgb(50, 100, 100, 100)), 0, 0, frm.Width, frm.Height);
for (int x = 5; x < e.ClipRectangle.Right + gap; x += gap * 2)
{
for (int y = 5; y < e.ClipRectangle.Bottom + gap; y += gap * 2)
{
// 计算文字起点位置
float x1 = cos30 * x - sin30 * y;
float y1 = sin30 * x + cos30 * y;
//画上文字
g.DrawString(text, font, new SolidBrush(color), x1, y1);
}
}
}
#region 在窗口结构中为指定的窗口设置信息
/// <summary>
/// 在窗口结构中为指定的窗口设置信息
/// </summary>
/// <param name="hwnd">欲为其取得信息的窗口的句柄</param>
/// <param name="nIndex">欲取回的信息</param>
/// <param name="dwNewLong">由nIndex指定的窗口信息的新值</param>
/// <returns></returns>
[DllImport("user32", EntryPoint = "SetWindowLong")]
private static extern uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
#endregion
#region 从指定窗口的结构中取得信息
/// <summary>
/// 从指定窗口的结构中取得信息
/// </summary>
/// <param name="hwnd">欲为其获取信息的窗口的句柄</param>
/// <param name="nIndex">欲取回的信息</param>
/// <returns></returns>
[DllImport("user32", EntryPoint = "GetWindowLong")]
private static extern uint GetWindowLong(IntPtr hwnd, int nIndex);
#endregion
private const uint WS_EX_LAYERED = 0x80000;
private const int WS_EX_TRANSPARENT = 0x20;
private const int GWL_EXSTYLE = (-20);
}
调用:
public Form1()
{
InitializeComponent();
new Watermark(this);
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容