Tech Off Thread

2 posts

Drawing on Controls

Back to Forum: Tech Off
  • JParrish

    I am not much of a desktop developer, but I have been getting into it with windows forms and C#.. and I have run into something that seems perplexing to me.

    I am creating a windows control that derives from ListView, and I am adding drag and drop functionality that will draw a line between items in the list to indicate where an item that is dropped will be inserted.

    My original approach was that upoin DragEnter being fired, I would set a Bitmap that is a priv class member to the current bitmap of the control.. I am doing this like so:

    this.ctrlbmp = new Bitmap(this.Width, this.Height, this.CreateGraphics());

    Then each time the DragOver event fires, I calculate based on the current Y position of the mouse, where to draw my line, and draw the bitmap on top of the control like such:

    this.CreateGraphics().DrawImage(bmp,0,0,this.Width,this.Height);

    I would then call this.Refresh() when DragLeave fires.

    The problem I have gotten into, seems to have to do with invalidating the control. The effect I get is that each line draws but is never removed as I drag across the list. I thought that it would be taken care of by repainting the entire control each time.

    If anyone can suggest reference material, or perhaps explain a more experienced approach, I would appreciate it greatly.

  • JParrish

    Well.. I couldn't stand this so when I got home I spent a little time working with it and realized that the best approach in my case is to track which item was last targetted and invalidate the region that I had painted over. It now works well and is much less intensive on resources. Something like this:

          Graphics g = this.CreateGraphics();
          Point currentpoint = this.PointToClient(new Point(e.X,e.Y));

          foreach(ListViewItem item in this.Items)
          {
            if(currentpoint.Y <= item.Bounds.Bottom && currentpoint.Y >= item.Bounds.Top)
            {
              if(item.Index != this.lastindextargetted)
              {
                g.DrawLine(new Pen(Brushes.Black,2),0,item.Bounds.Bottom,this.Width,item.Bounds.Bottom);
                if(this.lastindextargetted >= 0)
                {
                  this.Invalidate(new Rectangle(0,this.Items[this.lastindextargetted].Bounds.Bottom-2,this.Width,4));
                }

                this.lastindextargetted = item.Index;
              }
            }
          }

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.