Search code examples
.netdelphimouseeventpaneldelphi-prism

How to move Label within a panel using MouseMove event?


I know this should be very simple especially given all the information and example codes online, but for some reason I just can't get this to work.

I have a Label and a Panel on a winform. I want the label only to follow the mouse pointer when it enters and moves within the panel.

I got it working, but its location is totally shifted and it is always changing when you move the winform.

Here is the MouseMove and other events:

constructor MainForm;
begin
  InitializeComponent();
  label2.Visible:=false;
end;

method MainForm.panel1_MouseMove(sender: System.Object; e: System.Windows.Forms.MouseEventArgs);
begin
  //label2.Location := panel1.PointToScreen(e.Location);
  label2.Location := self.PointToScreen(e.Location);
  label2.Invalidate;
end;

method MainForm.panel1_MouseEnter(sender: System.Object; e: System.EventArgs);
begin
  label2.Visible:=true;
end;

method MainForm.panel1_MouseLeave(sender: System.Object; e: System.EventArgs);
begin
  label2.Visible:=false;
end;

Update As suggested by larstech, I modified the code, but the label is still showing up outside of the box as the image below is showing.

myimage

Thanks,


Solution

  • I don't know delphi-prism, but wouldn't it just be:

    label2.Location := e.Location;
    

    Since the Label is not a child control, try this:

    label2.Location := new Point(panel1.Left + e.Location.X, panel1.Top + e.Location.Y);
    

    Obviously, I may not have the syntax right.

    If you are just trying to move a ToolTip, this works in c#:

    private ToolTip _tips = new ToolTip();
    
    private void panel1_MouseMove(object sender, MouseEventArgs e) {
      _tips.Show("test", panel1, e.Location.X + 10, e.Location.Y + 10);
    }