我正在开展一个个人项目,我需要让客户画一个"签名"在一个新的弹出窗体上,通过处理事件(可能是点击鼠标和鼠标悬停)事件。
此签名必须存储在图像对象上,以便将其保存到数据库的varbinary(max)字段中。
谷歌搜索无法正常工作,不知道如何实现这一目标?
答案 0 :(得分:3)
我检查了我的触摸屏笔记本电脑,触地事件可以通过 MouseDown 事件处理,通过 MouseUp 进行修改,并通过 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();
}
}
}
}
签名在图像上绘制。因此,您可以根据需要在数据库中保存图像。