c#在桌面中绘图

c#中的GDI+虽然很方便我们程员绘图,但是如果我们想直接在电脑桌面上绘图的话就有困难了。

这就需要借助系统API来实现。

实现如下:

1、导入using System.Runtime.InteropServices;这是调用系统API必须要引入的

2、申明以下几个系统API函数:

  [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
      public static extern IntPtr GetDesktopWindow();//该函数返回桌面窗口的句柄。
      [DllImport("user32.dll", EntryPoint = "GetDCEx", CharSet = CharSet.Auto, ExactSpelling = true)]
      private static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hrgnClip, int flags);//获取显示设备上下文环境的句柄

 

3、在单击事件中使用以下代码进行桌面绘图:

    IntPtr desk = GetDesktopWindow();//获取桌面窗口句柄
            IntPtr deskDC = GetDCEx(desk, IntPtr.Zero, 0x403);//获取桌面设备上下文句柄
            Graphics g = Graphics.FromHdc(deskDC);
            g.DrawString("测试", new Font("宋体", 50, FontStyle.Bold), Brushes.Red, new PointF(100, 100));

 

以上步骤就完成了向桌面绘图的过程,是不是很简单呢,呵呵。不过目前我还不知道怎么擦除画在桌面上的内容。有知道的道友们可以交流下哦。

以下是源码:

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            timer1.Start();
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetDesktopWindow();
        [DllImport("user32.dll", EntryPoint = "GetDCEx", CharSet = CharSet.Auto, ExactSpelling = true)]
        private static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hrgnClip, int flags);



        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr desk = GetDesktopWindow();
            IntPtr deskDC = GetDCEx(desk, IntPtr.Zero, 0x403);
            Graphics g = Graphics.FromHdc(deskDC);
            g.DrawString("测试", new Font("宋体", 50, FontStyle.Bold), Brushes.Red, new PointF(100, 100));




        }

    }
}

 

posted @ 2012-09-28 20:20  kq2012  阅读(1453)  评论(0)    收藏  举报