How to detect and highlight rectangle on mouse hover

◇◆丶佛笑我妖孽 提交于 2019-12-12 15:10:00

问题


I have created a windows application control in C#.net to show some objects(things) in graphical mode. 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 .


回答1:


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


来源:https://stackoverflow.com/questions/12624193/how-to-detect-and-highlight-rectangle-on-mouse-hover

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!