想在桌面上涂鸦吗

我曾经说过一句致理名言:涂鸦是人生一大乐趣。

只要你懂得涂鸦之道,涂鸦是非常好玩的。在窗口上画多了,不爽了,想不想在桌面上画? 不要惊讶,这是可以的。

Graphics类可以用一个静态方法FromHwnd来创建实例,如果想在桌面上涂鸦,只要得到桌面的句柄就可以了。那么如何得到桌面的句柄呢?要用到一个非托管API,即

        [DllImport("User32.dll")]
        public extern static IntPtr GetDesktopWindow();


使用它可以得到桌面的句柄,只要有了句柄,就可创建Graphics,只要创建了Graphics对象,你想在它上面画个么鬼啊毛啊都可以了。

就像我今天给自己题了个辞,一起来欣赏一下我的书法吧。

为了使它爽一点,我用了一个Timer组件,并随机生成画刷颜色,让它有点闪烁的效果。

下面是部分代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;

namespace drawInDesktopApp
{
    public partial class Form1 : Form
    {
        Random rand = null;
        IntPtr hwndDesktop = IntPtr.Zero;
        public Form1()
        {
            InitializeComponent();
            hwndDesktop = GetDesktopWindow();
            rand = new Random();
            this.FormClosing += (s, a) => timer1.Stop();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            if (timer1.Enabled == false)
            {
                timer1.Start();
            }
        }

        private void DrawInScreen()
        {
            using (Graphics g = Graphics.FromHwnd(hwndDesktop))
            {
                // 获取屏幕的宽度和高度
                int scrWidth = Screen.PrimaryScreen.Bounds.Width;
                int scrHeight = Screen.PrimaryScreen.Bounds.Height;
                // 绘制文本
                string str = "致青春!!";
                Font font = new Font("华文行楷", 170f);
                // 创建渐变画刷
                Color txtcolor1 = Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256));
                Color txtcolor2 = Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256));
                // 计算文字的大小
                SizeF size = g.MeasureString(str, font);
                LinearGradientBrush lb = new LinearGradientBrush(
                    new RectangleF(new PointF(scrWidth /2, 0f), size),
                    txtcolor1,
                    txtcolor2, LinearGradientMode.Vertical);
                // 文本格式
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                g.DrawString(str, font, lb, new RectangleF(0f,0f,scrWidth,scrHeight),sf);
                font.Dispose();
                lb.Dispose();
            }
        }

        [DllImport("User32.dll")]
        public extern static IntPtr GetDesktopWindow();

        private void timer1_Tick(object sender, EventArgs e)
        {
            DrawInScreen();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/tcjiaan/article/details/8985994