设置运行时控件的位置

时间:2013-12-10 06:19:42

标签: c# .net winforms runtime

我在我的应用程序中添加了一个包含列表和toolStrip的listBox。这些用于选择控件以在面板中添加运行时。 (我添加了一个图像.toottrip和listBox分别位于左侧和右侧。)现在我对这些控件的处理是,

1 - 我从toolStrip或listBox中选择一个项目

2 - 进行运行时控制并显示在表单

3 - 在Mouse_Up事件中,控件在面板上设置(如果它在面板中。)

现在的问题是,如图所示,运行时控件不在光标的尖端。我希望这些运行时控件位于光标的顶端。

下面是图片。 enter image description here

编辑:下面是代码:

private void listBox_MouseDown(object sender, MouseEventArgs e)
{
    this.globalLabel1 = new Label();
            this.globalLabel1.Text = this.listBox.SelectedItem.ToString() + " : ";
    //other label properties like, tag, name, events, font etc.
}
private void listBox_MouseMove(object sender, MouseEventArgs e)
{
    if (this.globalLabel1 != null)
        {
            this.globalLabel1.Left = System.Windows.Forms.Cursor.Position.X
                - this.Location.X;

            this.globalLabel1.Top = System.Windows.Forms.Cursor.Position.Y
                - this.Location.Y;

            this.globalLabel1.Show();
            this.lPanel.SendToBack();
        }
}
private void listBox_MouseUp(object sender, MouseEventArgs e)
{
    this.globalLabel1.Parent = this.lPanel;
    this.globalLabel1.Anchor = AnchorStyles.Top | AnchorStyles.Left;

    this.globalLabel1.Left = Cursor.Position.X
            - /*Cursor.Size.Height -*/ this.lPanel.Location.X
            - this.Location.X;
    this.globalLabel1.Top = Cursor.Position.Y
            - /*Cursor.Size.Width -*/ this.lPanel.Location.Y
            - this.Location.Y;
}

感谢。

2 个答案:

答案 0 :(得分:2)

您必须将运行时添加的控件{strong>相对的Location设置为父级,您可以使用方法PointToClient,如下所示:

private void listBox_MouseUp(object sender, MouseEventArgs e) {
  globalLabel1.Parent = lPanel;
  globalLabel1.Anchor = AnchorStyles.Top | AnchorStyles.Left;

  globalLabel1.Location = lPanel.PointToClient(Cursor.Position);
}

答案 1 :(得分:1)

i)中。我不知道你为什么不使用Panel_MoveUP事件,因为你想把它放在面板上。

ⅱ)。在Panel_moveUp中,您必须通过命中和跟踪方法对光标位置进行一点位置更改,我不确定这是为什么会出现这种差异。

    private void listBox1_MouseDown(object sender, MouseEventArgs e)
    {
        this.globalLabel1 = new Label();
        this.globalLabel1.Text = this.listBox1.SelectedItem.ToString() + " : ";
        //other label properties like, tag, name, events, font etc.

    }

    //////////////////////////USE PANEL_MOVEUP EVENT//////////////

    private void lPanel_MouseMove(object sender, MouseEventArgs e)
    {
        if (this.globalLabel1 != null)
        {
            this.globalLabel1.Left = System.Windows.Forms.Cursor.Position.X-50 // Change
                - this.Location.X;

            this.globalLabel1.Top = System.Windows.Forms.Cursor.Position.Y-100 //Change
                - this.Location.Y;

            this.globalLabel1.Show();
            this.lPanel.SendToBack();
            this.lPanel.Controls.Add(globalLabel1);

        }
    }