【问题标题】:Moving control in runtime在运行时移动控制
【发布时间】:2014-09-21 07:24:12
【问题描述】:

我在移动面板上的标签时遇到问题。当我移动这个标签,到达顶部和左侧(0.0)时,标签尊重顶部和左侧。花费一半的屏幕,标签超出面板如图所示。

我的代码:

public partial class frmStandard : Form
{
    Point startposition;    
}

public void MouseDown(object sender, MouseEventArgs e)
{
    startposition = e.Location;
}

public void MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) 
    {   
        ((Label)sender).Left = Math.Max(0, e.X + ((Label)sender).Left - startposition.X);
        ((Label)sender).Top = Math.Max(0, e.Y + ((Label)sender).Top - startposition.Y);
    }
}

我需要标签不超过面板尺寸。代码中应该添加什么?

【问题讨论】:

  • 这可能是 Z 顺序问题,标签消失在该工具栏下方。一个简单的解决方法是将工具栏放在面板上。 MouseMove 代码也需要工作,一旦 Max() 完成工作,鼠标位置就会与标签位置不同步。避免使用 PointToScreen 出现问题。示例代码is here.

标签: c# winforms mousemove


【解决方案1】:

您需要检查其他边框。

为此,您必须使用包含 Panel 的维度数据。

本着保持动态的精神,就像您的代码一样,我使用他LabelParent 而不是只指Panel

private void MouseMove(object sender, MouseEventArgs e)
{
  Label L = (Label)sender;
  Rectangle PR = L.Parent.ClientRectangle;

  if (e.Button == MouseButtons.Left)
  {
     L.Left = Math.Min(Math.Max(0, e.X + L.Left - startposition.X), PR.Right - L.Width);
     L.Top = Math.Min( Math.Max(0, e.Y + L.Top - startposition.Y), PR.Bottom - L.Height);
  }
}

为了更通用,可以将Label 替换为Control,并让用户使用相同的代码移动其他Controls

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2018-03-22
    相关资源
    最近更新 更多