1. 程式人生 > >想在桌面上塗鴉嗎

想在桌面上塗鴉嗎

ref 分代 min rest ini 文本格式 toc == 一點

我曾經說過一句致理名言:塗鴉是人生一大樂趣。

只要你懂得塗鴉之道,塗鴉是非常好玩的。在窗口上畫多了,不爽了,想不想在桌面上畫? 不要驚訝,這是可以的。

Graphics類可以用一個靜態方法FromHwnd來創建實例,如果想在桌面上塗鴉,只要得到桌面的句柄就可以了。那麽如何得到桌面的句柄呢?要用到一個非托管API,即

[csharp] view plain copy
  1. [DllImport("User32.dll")]
  2. public extern static IntPtr GetDesktopWindow();


使用它可以得到桌面的句柄,只要有了句柄,就可創建Graphics,只要創建了Graphics對象,你想在它上面畫個麽鬼啊毛啊都可以了。

就像我今天給自己題了個辭,一起來欣賞一下我的書法吧。

技術分享圖片

技術分享圖片

為了使它爽一點,我用了一個Timer組件,並隨機生成畫刷顏色,讓它有點閃爍的效果。

下面是部分代碼。

[csharp] view plain copy
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Drawing.Drawing2D;
  11. using System.Runtime.InteropServices;
  12. namespace drawInDesktopApp
  13. {
  14. public partial class Form1 : Form
  15. {
  16. Random rand = null;
  17. IntPtr hwndDesktop = IntPtr.Zero;
  18. public Form1()
  19. {
  20. InitializeComponent();
  21. hwndDesktop = GetDesktopWindow();
  22. rand = new Random();
  23. this.FormClosing += (s, a) => timer1.Stop();
  24. }
  25. private void button1_Click(object sender, EventArgs e)
  26. {
  27. this.WindowState = FormWindowState.Minimized;
  28. if (timer1.Enabled == false)
  29. {
  30. timer1.Start();
  31. }
  32. }
  33. private void DrawInScreen()
  34. {
  35. using (Graphics g = Graphics.FromHwnd(hwndDesktop))
  36. {
  37. // 獲取屏幕的寬度和高度
  38. int scrWidth = Screen.PrimaryScreen.Bounds.Width;
  39. int scrHeight = Screen.PrimaryScreen.Bounds.Height;
  40. // 繪制文本
  41. string str = "致青春!!";
  42. Font font = new Font("華文行楷", 170f);
  43. // 創建漸變畫刷
  44. Color txtcolor1 = Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256));
  45. Color txtcolor2 = Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256));
  46. // 計算文字的大小
  47. SizeF size = g.MeasureString(str, font);
  48. LinearGradientBrush lb = new LinearGradientBrush(
  49. new RectangleF(new PointF(scrWidth /2, 0f), size),
  50. txtcolor1,
  51. txtcolor2, LinearGradientMode.Vertical);
  52. // 文本格式
  53. StringFormat sf = new StringFormat();
  54. sf.Alignment = StringAlignment.Center;
  55. sf.LineAlignment = StringAlignment.Center;
  56. g.DrawString(str, font, lb, new RectangleF(0f,0f,scrWidth,scrHeight),sf);
  57. font.Dispose();
  58. lb.Dispose();
  59. }
  60. }
  61. [DllImport("User32.dll")]
  62. public extern static IntPtr GetDesktopWindow();
  63. private void timer1_Tick(object sender, EventArgs e)
  64. {
  65. DrawInScreen();
  66. }
  67. }
  68. }

想在桌面上塗鴉嗎