How can we get the location relative to the shape of the window?

I am implementing an application that can be dragging and dropping images on a panel, so I want to make sure that the image is placed inside the panel and the whole image is displayed when the image is displayed. In this case, I want to get the current cursor position when I do a drag event. So how can I get the cursor location associated with the panel? Here is the dragdrop panel event method.

private void panel1_DragDrop(object sender, DragEventArgs e) { Control c = e.Data.GetData(e.Data.GetFormats()[0]) as Control; if (c != null) { if (eX < 429 && eX > 0 && eY<430 && eY>0) { c.Location = this.panel1.PointToClient((new Point(eX, eY)));** this.panel1.Controls.Add(c); } } } 
+4
source share
1 answer

You can get the coordinates of the cursor using Cursor.Position , this will give you the screen coordinates. you can pass them to PointToClient(Point p)

 Point screenCoords = Cursor.Position; Point controlRelatedCoords = this.panel1.PointToClient(screenCoords); 

Although, I am sure that DragEventArgs.X and DragEventArgs.Y are already the coordinates of the screen. Your problem probably is

  if (eX < 429 && eX > 0 && eY<430 && eY>0) 

It looks like this will check the panel coordinates, while eX and eY are the screen coordinates at this point. Instead, before checking borders: turn them into panels,

  Point screenCoords = Cursor.Position; Point controlRelatedCoords = this.panel1.PointToClient(screenCoords); if (controlRelatedCoords.X < 429 && controlRelatedCoords.X > 0 && controlRelatedCoords.Y < 430 && controlRelatedCoords.Y > 0) { } 
+3
source

Source: https://habr.com/ru/post/1302235/


All Articles