Link to home
Start Free TrialLog in
Avatar of Todd_Anderson
Todd_Anderson

asked on

Need to update drawing after a key is pressed

I have a simple program (Visual Basic.NET 2003) that draws a crosshair.  I need to be able to move the crosshair up, down, left and right when the user pushes the standard arrow keys on the keyboard.  I am drawing the crosshair in the Form1_Paint event using variables (x and y) with form-wide scope.  I am updating x and y in the Form1_KeyDown event.  Everything is working fine except that the drawing is not updating.  It updates correctly when I drag another window over it.

All this is as expected.  My question is, how do I refresh, updated or redraw my drawing at the end of my Form1_KeyDown event after I have incremented my x and y variables based on the user's input?
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

After you update the x and y coordinates, issue a

    Me.Refresh()

which will cause your Paint event to be fired.

~IM
Avatar of Todd_Anderson
Todd_Anderson

ASKER

Thanks Idle Mind.  It works as I hoped except for one thing.  I am getting a lot of flashing each time the refresh occurs.  Quick bars of 20 or so horizontal lines show up briefly every few keystrokes.  Anyway to fix that?
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Idle Mind.  I'll give those two ideas a try.  What about manually erasing the crosshair and then redrwing it in the Form1_KeyDown event?
If your backcolor is the same everywhere then you could certainly erase it and then redraw it from the KeyDown event.

The only problem with that approach is that the crosshair won't be persistent then since it is not in the Paint event.  If you minimize the window or pass another window over your form, then the crosshair will be gone.

~IM
Ah, very true.  I just did an experiment and it stopped the flashing.  I had a g.Clear(Color.Black) line in my Form1_Paint event.  When I commented it out the flashing stopped.  Now I just need to figure out how to do the clear and set the background to black outside of the Paint event.  I'll also try your other suggestions.
Set the background color using the BackColor property at design time.  Then you shouldn't need the Clear() call.
Awesome!  It works great.  Thanks a lot Idle Mind.