分享

c#在桌面中绘图

 羊玉wngbx 2019-12-03

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




        }

    }
}
复制代码

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多