2014-09-21 27 views
1

我在移動面板上的標籤時出現問題。當我移動此標籤時,達到頂部並離開(0.0),標籤尊重頂部和左側。要花費一半的屏幕,標籤超出面板,如圖所示。在運行時移動控件

enter image description here

我的代碼:

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); 
    } 
} 

我需要的標籤不超過面板size.What應在代碼中添加?

+0

它可能是一個Z順序問題,該標籤在該工具欄下消失。一個簡單的解決方法是*不*將工具欄放在面板上。 MouseMove代碼也需要工作,一旦Max()完成其工作,鼠標位置與標籤位置不同步。避免使用PointToScreen出現問題。示例代碼[在這裏](http://stackoverflow.com/a/25591801/17034)。 – 2014-09-21 09:05:26

回答

4

您需要檢查其他邊界。

您必須使用包含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); 
    } 
} 

爲了保持更加普遍,人們可以替換LabelControl,並讓用戶移動其他Controls圍繞相同的代碼段。