VB.NET How to clear the form's background - vb.net

I am trying to create a simply bouncy ball application in VB net;
I am using a timer and the FillEllipse() method to try ad create a new circle at every tick of the timer.
Code:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim Gr As Graphics = Me.CreateGraphics
Gr.FillEllipse(Brushes.Teal, X, Y, W, H)
CollisionDetect()
X = X + X_Dir
Y = Y + Y_Dir
Gr.Dispose()
End Sub
The result? The form continously draws onto itself, without clearing the last circle. This means that you end up with a 'line' of spheres together.
To clarify:
X is well, the X-Coords
Y is Y- Y-Coords
X_Dir is an integer, it is added to every iteration of the loop so the next time the loop iterates, it'll be at a different location;
Y_Dir is the same but for the Y Coords;
CollisionDetect() Is empty. It is yet to be filled, it will handle the collision with the sides of the forms.
W, H are width and height, respectively.
Ideas?

Usually painting is done when the Paint event is fired. Add a Panel control with the desired background color to your form. Handle the Paint event of your panel
Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint
e.Graphics.FillEllipse(Brushes.Teal, X, Y, W, H)
End Sub
The panel will always automatically be cleared before you draw.
Change the timer tick event handler to
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Panel1.Invalidate() ' This triggers the Paint event
CollisionDetect()
X = X + X_Dir
Y = Y + Y_Dir
End Sub
Note that the Paint event is fired automatically, if the panel was hidden by another form, for instance, and has to be redrawn. If the computer is busy and cannot paint, some paint events may be skipped. Therefore keep your game logic (calculation) in Timer1_Tick.
If you prefer to draw directly on the form, you can do that by using the form's paint event instead of the panel's paint event and by calling Me.Invalidate() instead of Panel1.Invalidate().

Related

draw coordinate Two dimensions graph of (x-y) visual basic

hey every one I want to make a program that able to draw coordinate graph of Two dimensions of (x-y).when I enter a value in (x) text box and (y) text box and hit draw button it well draw the graph in the blue picture box . I searched in web sit but I found only one method that draw using the mouse and this not what I want .This is the image of the program and and it supposed to draw in white line like this image
Private Sub PictureBox2_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox2.MouseMove
Static last As Point
If e.Button = Windows.Forms.MouseButtons.Left Then
PictureBox2.CreateGraphics.DrawLine(Pens.White, last.X, last.Y, e.X, e.Y)
End If
last = e.Location
End Sub
this is the code that I found that draw using the mouse
You should use the Graphic class inside the panel's Paint event
Private Sub Panel1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs)
' Create pen.
Using blackPen As New Pen(Color.Black, 3)
' Create points that define line.
Dim point1 As New Point(100, 100)
Dim point2 As New Point(500, 100)
' Draw line to screen.
e.Graphics.DrawLine(blackPen, point1, point2)
End Using
End Sub
Then call Panle1.Invalidate() to fire the Paint event
It would be good to have a bit more details of your code, especially how and in what class you store the X and Y coordinate. By the way you draw a line between 2 points so you would need two sets of X and Y coordinate boxes on your form.
After that it is as easy as what you found on the internet using the DrawLine method (https://msdn.microsoft.com/en-us/library/system.drawing.graphics.drawline(v=vs.110).aspx), you just needs to fire it from the Click event of your "draw" button.
Hi again Ahmed
Here is a simple sample of a form that would draw a line when button is clicked. Of course it would need more bootstrapping to make sure user only enter integer value for the number of pixels and in its basic form, (0,0) is the top left of the panel but it can easily be converted for a bottom left approach...
and
Class Form1
Private Sub cmdDraw_Click(sender As Object, e As EventArgs) Handles cmdDraw.Click
Dim x1 As Integer = Integer.Parse(txtX1.Text)
Dim y1 As Integer = Integer.Parse(txtY1.Text)
Dim x2 As Integer = Integer.Parse(txtX2.Text)
Dim y2 As Integer = Integer.Parse(txtY2.Text)
pnlMap.CreateGraphics.DrawLine(New Pen(Color.Black), x1, y1, x2, y2)
End Sub
End Class

How to use the Paint event more than once on a form?

Okay, so I am trying to make a program that each time you click (doesn't matter where) a random colored, and sized circle appears where you happened to click. however, the only way I can add a shape is via Paint event. here is the code I have now:
Private Sub Form1_Paint(ByVal Sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Using Brush1 As New SolidBrush(Color.Orange)
e.Graphics.FillEllipse(Brush1, MousePosition.X, MousePosition.Y, 100, 100)
End Using
End Sub
I need to know a line of code that I can use in a mouse click event, that will re-run this sub. I know how to change the size, and make it random, I just don't know how to run this sub multiple times, more precisely; run this sub once after each mouse click. If someone can help, I would appreciate it!
Just as Plutonix explained, a refresh is handled by calling the Invalidate method.
The thing you need to remember is that whatever is painted on a surface is not persistent, so you need to redraw the whole screen every time. There are, of course, many ways in which this can be optimized for performance purposes, as this process can be extremely CPU intensive; specially, since GDI+ is not hardware accelerated.
So, what you need to do is:
Record every click (x, y position) and store it
Since the radius of each circle is random, determine the radius when the user clicks the form, then store it along with the x, y position of the click
Then, have the Paint event re-draw each stored sequence of clicks (with their respective radii) and re-draw each circle over and over.
Here's an implementation that will do the trick. Just paste this code inside any Form's class to test it:
Private Class Circle
Public ReadOnly Property Center As Point
Public ReadOnly Property Radius As Integer
Public Sub New(center As Point, radius As Integer)
Me.Center = center
Me.Radius = radius
End Sub
End Class
Private circles As New List(Of Circle)
Private radiusRandomizer As New Random()
Private Sub FormLoad(sender As Object, e As EventArgs) Handles MyBase.Load
Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True) ' Not really necessary in this app...
Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
Me.SetStyle(ControlStyles.ResizeRedraw, True)
Me.SetStyle(ControlStyles.UserPaint, True)
End Sub
Private Sub FormMouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
circles.Add(New Circle(New Point(e.X, e.Y), radiusRandomizer.Next(10, 100)))
Me.Invalidate()
End Sub
Private Sub FormPaint(sender As Object, e As PaintEventArgs) Handles Me.Paint
Dim g As Graphics = e.Graphics
g.Clear(Color.Black)
Using p As New Pen(Color.White)
For Each c In circles
g.DrawEllipse(p, c.Center.X - c.Radius \ 2, c.Center.Y - c.Radius \ 2, c.Radius, c.Radius)
Next
End Using
End Sub
Here's what you'll get after a few clicks on the form

Mouse hovering event

I want to do an mouse hovering event, when the mouse is over an button I want to change button text color and font size, I have try this code but doesn't work:
Private Sub Command1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Command1.ForeColor.MediumBlue()
Command1.FontSize = 10
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Command1.ForeColor.White()
Command1.FontSize = 8
End Sub
Can anyone give me a suggestion i have search on Google and try different ways with mouse event handler but didn't work.
First, instead of tracking every mouse move, you can rely on MouseEnter and MouseLeave events of the button.
Second, do not forget to add Handles <Control>.<Event> clause at the declaration of your event-handling procedures.
Result:
Private Sub Command1_MouseEnter(sender As Object, e As EventArgs) _
Handles Command1.MouseEnter
Command1.FontSize = 10
End Sub
Private Sub Command1_MouseLeave(sender As Object, e As EventArgs) _
Handles Command1.MouseLeave
Command1.FontSize = 8
End Sub
Also please do not forget that some users are preferring keyboard control.
This means that
You might want to equip the button with an accelerator.
Command1.Text = "&Launch" (now Alt+L activates the button)
Note: accelerator character for winforms is &, for wpf is _.
You might want to make your entry/leave effect also when the button receives/looses keyboard focus (focus is moved using Tab and Shift+Tab key).
You can try making your changes into MouseEnter and MouseLeave
Private Sub RightButton_MouseEnter(sender As System.Object, e As System.EventArgs) Handles RightButton.MouseEnter
RightButton.ForeColor = Color.AliceBlue
RightButton.Font = New Font(RightButton.Font, 12)
End Sub
Private Sub RightButton_MouseLeave(sender As System.Object, e As System.EventArgs) Handles RightButton.MouseLeave
RightButton.ForeColor = Color.White
RightButton.Font = New Font(RightButton.Font, 10)
End Sub

How to change progress bar value by dragging mouse in vb.net

I am developing a media player and I'm trying to change value of Progress Bar using mouse cursor.
what i want is to set the value of progress bar where mouse cursor points after clicking + Dragging.
A progress bar is not the correct control to use for this. You should use a TrackBar instead.
But it can be made to work, with about -10 elegance points. The trickiest problem with ProgressBar is that it animates progress. That makes it slow to respond to your mouse moves. That animation can be disabled, but not perfectly. Closest you can get is:
Private Shared Sub ChangeProgress(bar As ProgressBar, e As MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim mousepos = Math.Min(Math.Max(e.X, 0), bar.ClientSize.Width)
Dim value = CInt(bar.Minimum + (bar.Maximum - bar.Minimum) * mousepos / bar.ClientSize.Width)
'' Disable animation, if possible
If value > bar.Value And value < bar.Maximum Then
bar.Value = value + 1
bar.Value = value
Else
bar.Value = value
End If
End If
End Sub
And call it from MouseDown and MouseMove event handlers:
Private Sub ProgressBar1_MouseMove(sender As Object, e As MouseEventArgs) Handles ProgressBar1.MouseMove
ChangeProgress(ProgressBar1, e)
End Sub
Private Sub ProgressBar1_MouseDown(sender As Object, e As MouseEventArgs) Handles ProgressBar1.MouseDown
ChangeProgress(ProgressBar1, e)
End Sub
It is workable, you'll notice that getting to 100% is a bit awkward. But, really, use a TrackBar instead. It was made to do this.

Drag a label and make it leave a black trail behind it

I am working on a project and I have a label in a picturebox that I need to drag around and while dragging around have it leave a black trail on the picturebox. I am stumped as to how to make this happen. The label is 15x15 and is moved using the mouse and mousedown, mousemove, and mouseup events. During the mousemove the label needs to draw black wherever the label has covered. Thanks for the help!
You need to override the Form's OnPaint() method and then track the offset of the mouse Location from the point of drag origniation. This is essentially implementing an animated effect, so you will need to fire a redraw timer on the Label's drag start, paint the "tail" at a previous drag coordinate, repeating as your drag op moves the mouse coordinates past a certain threshold or certain speed. This will require some playing around to get the effect just right, but its fairly easy to implement.
Get started here: http://msdn.microsoft.com/en-us/library/3e40ahaz(v=vs.110).aspx
Lets say you have a background image in picturebox. Create a bitmap with picturebox dimensions:
Private pctBoxImage As Bitmap
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
pctBoxImage = New Bitmap(PictureBox1.Width, PictureBox1.Height, Drawing.Imaging.PixelFormat.Format24bppRgb)
pctBoxImage = CType(PictureBox1.BackgroundImage, Bitmap)
End Sub
If you dont have a background image just some color:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
pctBoxImage = New Bitmap(PictureBox1.Width, PictureBox1.Height, Drawing.Imaging.PixelFormat.Format24bppRgb)
Dim objGraphics As Graphics = Graphics.FromImage(pctBoxImage)
objGraphics.Clear(PictureBox1.BackColor)
objGraphics.Dispose()
End Sub
When ever you move the label:
Dim pt as Point
'pt = PictureBox1.PointToClient(Cursor.Position)
pt = Label1.PointToScreen(New Point(0, 0))
pt = PictureBox1.PointToClient(pt)
Dim objGraphics As Graphics = Graphics.FromImage(pctBoxImage)
objGraphics.FillRectangle(Brushes.Black, pt.X, pt.Y, 15, 15)
objGraphics.Dispose()
PictureBox1.BackgroundImage = pctBoxImage
valter