Is there any way to call the OnPaint() method after certain conditions have been cleared?

1k views Asked by At

My desktop is really messy at the moment so I decided to create a program where you can drag a file it and it creates a shortcut. When the file is dragged in, I grab the file's icon and name and save it, then draw them to the WinForm through OnPaint(). I'm having trouble with this though, since even before I can drag the file into the form, the OnPaint() draws a huge red X and doesn't update. Here is my code (it's a picture):

enter image description here

And the OnPaint method:

enter image description here

My question is that is there anyway to delay the OnPaint() method to wait until it acquires the certain data it needs to draw properly, or any other drawing method I could use to paste the icon+file name to the WinForm?

P.S: I've tried using Thread.Sleep, but then I realized it sleeps the main thread so the Drag/Drop processes can't occur

1

There are 1 answers

0
Simon Whitehead On BEST ANSWER

I see two options.

The first is what I said in my comment.. invalidate the form to cause OnPaint to be recalled after the drag drop:

foreach (string path in filePath)
{
    // your other code here (PS: Paste code next time)
}

this.Invalidate();

Your other option.. is to use a flag that you can check in OnPaint:

bool canDraw = false;

// dragdrop event:

foreach (string path in filePath)
{
    // your other code here (PS: Paste code next time)
}

canDraw = true;

// OnPaint:

if (canDraw) {
    // do your painting here

    canDraw = false;
}

base.OnPaint(e); // make sure you defer to the base painting method too

The second option effectively delays your painting until you say its okay.. but only your custom painting. You leave the base.OnPaint call out of your conditional so that it can always paint when it needs to.