【问题标题】:moving a form by holding on a label按住标签移动表格
【发布时间】:2015-08-26 09:18:37
【问题描述】:

我正在尝试创建一个以表格为中心的标签,该表格需要我使用label.dock = dockStyle.Fill。因此我尝试实现代码,这意味着当我按住标签时,我可以移动表单。这是我到目前为止所拥有的:

private void messageIndicator_MouseUp(object sender, MouseEventArgs e)
    {
        window.AllowTransparency = true;
        window.TransparencyKey = window.TransparencyKey = window.BackColor;
        isDragging = false;
    }

    void messageIndicator_MouseHover(object sender, EventArgs e)
    {
        window.AllowTransparency = false;
    }

    private void messageIndicator_MouseDown(object sender, MouseEventArgs e)
    {
        // Set the drag mode
        isDragging = true;

        // Get the initial location
        lastLocation = e.Location;
    }

    private void messageIndicator_MouseMove(object sender, MouseEventArgs e)
    {
        // Only drag if in correct state (mouse down)
        if (isDragging)
        {
            // The parameter sender is the form object
            Form f = (Form)sender;

            // Calculate the new location and update the form
            f.Location = new Point((f.Location.X - lastLocation.X) + e.X, (f.Location.Y - lastLocation.Y) + e.Y);
            f.Update();
        }
    }

messageIndicator 是表单上的标签。执行Form f = (form)sender 时确实会崩溃。非常感谢您的帮助:)

【问题讨论】:

  • 不,发件人必须是Label。它引发了什么异常?
  • Pear GIS.exe 中发生“System.InvalidCastException”类型的未处理异常附加信息:无法将“System.Windows.Forms.Label”类型的对象转换为“System.Windows.Forms”类型.Form'。

标签: c# forms window label mouseevent


【解决方案1】:

试试这个,

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

private void YourLabel_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{     
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
    }
}

来源:Article

【讨论】:

  • 错误 176 当前上下文中不存在名称“Handle”
  • @Khal786 很抱歉,如果您还没有解决此问题,请出示您的代码。
  • @Khal786 如果您在表格内工作,那么Handle 不会有任何问题。
猜你喜欢
  • 1970-01-01
  • 2014-02-03
  • 2020-03-18
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多