c# - 如何正确存储位置
问题描述
我有这个表单,它允许用户通过鼠标移动单击并拖动它们来创建图片框。每次添加图片框或将图片框移动到新位置时,如何存储图片框所在位置的坐标(位置)?我正在尝试将它们作为导出字符串存储在列表中。
private void Form_MouseClick(object sender, MouseEventArgs e)
{
// create new control
PictureBox pictureBox = new PictureBox();
pictureBox.Location = new Point(e.X, e.Y);
pictureBox.BackColor = Color.Red;
this.Controls.Add(pictureBox);
// bind event for each PictureBox
pictureBox.MouseDown += pictureBox_MouseDown;
pictureBox.MouseUp += pictureBox_MouseUp;
pictureBox.MouseMove += pictureBox_MouseMove;
}
Point mouseDownPoint = Point.Empty;
Rectangle rect = Rectangle.Empty;
bool isDrag = false;
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDownPoint = e.Location;
rect = (sender as PictureBox).Bounds;
}
}
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (isDrag)
{
isDrag = false;
(sender as PictureBox).Location = rect.Location;
this.Refresh();
}
reset();
}
}
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDrag = true;
rect.Location = this.PointToClient((sender as PictureBox).PointToScreen(new Point(e.Location.X - mouseDownPoint.X, e.Location.Y - mouseDownPoint.Y)));
this.Refresh();
}
}
private void reset()
{
mouseDownPoint = Point.Empty;
rect = Rectangle.Empty;
isDrag = false;
}
解决方案
要保存每个图片框的位置,可以定义一个字典来保存键值对。
首先,将字典定义box_location_Pairs
为全局变量。
然后在“单击创建新图片框”时将新项目添加到字典中。
Dictionary<PictureBox, Point> box_location_Pairs = new Dictionary<PictureBox, Point>();
// ...
private void Form_MouseClick(object sender, MouseEventArgs e)
{
PictureBox pictureBox = new PictureBox();
pictureBox.Location = new Point(e.X, e.Y);
box_location_Pairs.Add(pictureBox, pictureBox.Location);
// ...
}
如果图片框被移动,修改它的值。
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (isDrag)
{
isDrag = false;
(sender as PictureBox).Location = rect.Location;
box_location_Pairs[sender as PictureBox] = rect.Location; // modifty key-value pair
this.Refresh();
}
reset();
}
}
推荐阅读
- java - IntelliJ - JavaFX 和 JavaDoc:两个版本的模块
- node.js - 来自 docker 映像的命令未传递到管道
- r - 使用R中的欧几里得距离在曲线上查找X,Y坐标
- java - 在我们的服务上使用 DynamoDB 或 Redis
- python - 如何在python的数据框列中删除包含数字的单词
- rust - 为什么在包含闭包的选项中“一种类型比另一种更通用”?
- java - 模块描述符的主类属性是否仅适用于 JAR 文件?
- ffmpeg - ffmpeg 剪切视频并将音频放在它的中间
- mysql - 无法使用 flyway 配置文件迁移 mysql 脚本
- c# - 新 Azure Functions 项目中的“System.Reflection.AssemblyCompanyAttribute”属性重复