简体   繁体   中英

How to detect and highlight rectangle on mouse hover

I have created a windows application control in C#.net to show some objects in graphical mode. To do so I created a rectangles depend on number of items I got in list and plot it over control by using Control OnPaint event.

Now I want to highlight that rectangle if mouse hovering on it.

Please check attached image for more clarity & suggest me how can I achieve it .

在此处输入图片说明

Did you check the classical DrawCli example? It shows how a basic application should manage objects and tools.

In short you should re-enumerate your list inside MouseMove event, get the item's rect and set its IsFocused property to true if mouse pointer is inside that rect. Then redraw if something changed. You may even do that inside your OnPaint (check current mouse position) but then you have to always redraw everything inside MouseMove (and it's a very bad idea).

Kind of pseudo-code to explain what I mean:

protected override void OnPaint(PaintEventArgs e)
{
   foreach (GraphicalObject obj in Objects)
   {
      if (!obj.IsVisible)
            continue;

      Rectangle rect = obj.GetBounds(e.Graphics);
      if (!rect.Intersects(e.ClipRectangle))
         continue;

      obj.Draw(e.Graphics);
   }
}

GraphicalObject is the base type for all objects you can put on the screen. Objects is a property that contains the collection of them ( GraphicalObjectCollection , for example). Now you code may be like this (note that this is far aways from true code, it's just an example of a general technique):

protected override OnMouseMove(MouseMoveEventArgs e)
{
   bool needToRedraw = false;

   using (Graphics g = CreateGraphics())
   {
      foreach (GraphicalObject obj in Objects)
      {
         if (!obj.IsVisible)
               continue;

         Rectangle rect = obj.GetBounds(e.Graphics);
         if (rect.Contains(e.Location))
         {
            if (!obj.IsFocused)
            {
               obj.IsFocused = true;
               needToRedraw = true;
            }
         }
         else
         {
            if (obj.IsFocused)
            {
               obj.IsFocused = false;
               needToRedraw = true;
            }
         }

         obj.Draw(e.Graphics);
      }
   }

   if (needToRedraw)
      Invalidate();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM