想在桌面上塗鴉嗎
阿新 • • 發佈:2018-03-31
ref 分代 min rest ini 文本格式 toc == 一點
我曾經說過一句致理名言:塗鴉是人生一大樂趣。
只要你懂得塗鴉之道,塗鴉是非常好玩的。在窗口上畫多了,不爽了,想不想在桌面上畫? 不要驚訝,這是可以的。
Graphics類可以用一個靜態方法FromHwnd來創建實例,如果想在桌面上塗鴉,只要得到桌面的句柄就可以了。那麽如何得到桌面的句柄呢?要用到一個非托管API,即
[csharp] view plain copy- [DllImport("User32.dll")]
- public extern static IntPtr GetDesktopWindow();
使用它可以得到桌面的句柄,只要有了句柄,就可創建Graphics,只要創建了Graphics對象,你想在它上面畫個麽鬼啊毛啊都可以了。
就像我今天給自己題了個辭,一起來欣賞一下我的書法吧。
為了使它爽一點,我用了一個Timer組件,並隨機生成畫刷顏色,讓它有點閃爍的效果。
下面是部分代碼。
[csharp] view plain copy- 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();
- }
- }
- }
想在桌面上塗鴉嗎