代码分享:给窗体添加水印

有时需要给窗体添加水印,可能是未注册,或者已审核单据等。

截图如下

image


代码:(有一个问题没解决  就是切换别的程序是  水印不会自动消失,会覆盖到别的程序上   有兴趣的同学可以试试 Active事件 控制一下)

public class Watermark
     {
         //覆盖水印到底层窗体
         //调用方式Watermark wm = new Watermark(需要覆盖水印的窗体);
         public Watermark(Form ctrl)
         {
             Form frm = new Form();
             ctrl.SizeChanged += delegate
             {
                 frm.Size = ctrl.Size;
             };

            ctrl.Move += delegate
             {
                 frm.Location = ctrl.Location;
             };

            frm.TopMost = true;
             frm.FormBorderStyle = FormBorderStyle.None;
             frm.Opacity = 0.3;
             frm.ShowInTaskbar = false;

            string status = "审核通过";

            Bitmap myBitmap = new Bitmap(128, 128);
             myBitmap.MakeTransparent(Color.Transparent);

            Graphics g = Graphics.FromImage(myBitmap);

            //Graphics g = this.CreateGraphics();
             //g.Clear(Color.White);
             //抗锯齿
             g.SmoothingMode = SmoothingMode.AntiAlias;
             g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
             //平移画布到需要画印章的位置
             g.TranslateTransform(0, 64);
             //逆时针旋转30度
             g.RotateTransform(-30);
             //画一个椭圆框
             //SizeF sf = g.MeasureString(status, new Font("微软雅黑", 16, FontStyle.Bold));
             //g.DrawEllipse(new Pen(Color.Red, 3), 0, 0, sf.Width + 10, sf.Height + 10);
             //画上文字
             g.DrawString(status, new Font("微软雅黑", 16, FontStyle.Bold), Brushes.Red, 5, 5);

            myBitmap.Save("png.png", ImageFormat.Png);
             frm.BackgroundImage = myBitmap;
             frm.Show();


             GetWindowLong(frm.Handle, GWL_EXSTYLE);
             SetWindowLong(frm.Handle, GWL_EXSTYLE, WS_EX_TRANSPARENT | WS_EX_LAYERED);

        }
         #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);
     }

猜你喜欢

转载自www.cnblogs.com/myrapid/p/11790617.html