C# 允许用户通过鼠标/屏幕点击在 winform 上绘图

标签 c# graph graphics drawing

我正在开发一个个人项目,我需要允许客户在新的弹出表单上绘制“签名”,这是通过处理事件(可能是单击和鼠标悬停)事件来实现的。

此签名必须存储在图像对象上,以便将其保存到数据库上的 varbinary(max) 字段。

谷歌搜索不起作用,知道如何实现这一点吗?

最佳答案

我检查了我的触摸屏笔记本电脑,touchdown事件可以通过MouseDown事件处理,touchup可以通过MouseUp事件处理,touchmove可以通过MouseMove事件处理表格。

注意:我的机器同时支持触摸和鼠标。我不确定仅触摸设备或机器。

以下代码允许您通过触摸/鼠标交互在表单上绘图。

public partial class Form1 : Form
{
    Image signature;
    bool clicked = false;
    Point previousPoint;

    public Form1()
    {
        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Paint += Form1_Paint;
        this.MouseDown += Form1_MouseDown;
        this.MouseUp += Form1_MouseUp;
        this.MouseMove += Form1_MouseMove;
        this.MouseLeave += Form1_MouseLeave;

        this.FormClosing += Form1_FormClosing;
    }

    void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        //Dispose signature after closing the form to avoid memory leak
        signature.Dispose();
    }

    void Form1_Paint(object sender, PaintEventArgs e)
    {
        if (signature != null)
            e.Graphics.DrawImage(signature, 0, 0);
    }

    void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        clicked = true;
        previousPoint = e.Location;
    }

    void Form1_MouseLeave(object sender, EventArgs e)
    {
        clicked = false;
    }

    void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        clicked = false;
    }

    void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (clicked)
        {
            if (signature == null)
                signature = new Bitmap(this.Width, this.Height);
            using (Graphics g = Graphics.FromImage(signature))
            {
                g.DrawLine(Pens.Black, previousPoint, e.Location);
                previousPoint = e.Location;
                this.Invalidate();
            }
        }
    }
}

签名绘制在图像上。这样您就可以根据需要将图像保存到数据库中。

关于C# 允许用户通过鼠标/屏幕点击在 winform 上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880165/

相关文章:

c# - linq error 为 hashset 定义的默认值

c# - 在 trycatch block 中捕获 403 WebException?

c# - 如何从数组创建将生成重复键的字典

data-structures - 图表-如果我用哈希表替换邻接列表中的每个链表,会有什么缺点?

c++ - 普里姆算法C++

c++ - 从 vtk 渲染计算相机空间坐标

android - 能否为 Android Canvas 上的 Drawable 禁用抗锯齿功能?

c# - 从 http 服务流式传输大文件

c++ - 为什么要用树状数据结构来表示文字冒险游戏中的数据?

algorithm - 计算或检测从线路经过的 Sprite