Animated sliding form VB.Net - vb.net

EDIT:
So now my form location is established as per ZackRyan's answer but I still can't get it to move back to original location after it slides left.
This is the code I expect to move the form to original location
Private Sub Label7_Click(sender As Object, e As EventArgs) Handles Label7.Click
Me.Close()
'Testing.StartPosition.CenterScreen
For MoveLeft = Form2.Location.X To 30 Step 1
Form2.Left = MoveLeft
Form2.Refresh()
Threading.Thread.Sleep(0)
Next
End Sub
This is the original location:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim xLoc = Me.Location.X
Dim yLoc = Me.Location.Y
Me.Location = New Point(xLoc, yLoc)
End Sub
------------------------------------------//--------------------------------------------------
I'm creating a windows app where a form moves to the left smoothly, all ok with this. My problem is bringing it back to it's initial position.
The form is loaded with default position set to CenterScreen I then use the following to move it to the left:
Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.Click
For MoveLeft = FormStartPosition.CenterScreen To 18 Step 1
Me.Left -= MoveLeft
Me.Refresh()
Threading.Thread.Sleep(1)
Next
To make it go back I'm trying the inverse:
Private Sub Label9_Click(sender As Object, e As EventArgs) Handles Label9.Click
For MoveLeft = FormStartPosition.CenterScreen To 18 Step 1
Me.Left = MoveLeft
Me.Refresh()
Threading.Thread.Sleep(1)
Next
This only works partially. The form moves to the right which is what is required, but instead of moving from the current position to CenterScreen, if moves completely at the bottom of the page.
I basically need it to return to its original center screen position smoothly.

Simply store the form's position(on form load) in some variables...
E.g.
Dim xLoc = MyForm.Location.X
Dim yLoc = MyForm.Location.Y
'Or
Dim xLoc = MyForm.Bounds.Left
Dim yLoc = MyForm.Bounds.Top
'or
Dim loc As Point = MyForm.Location
then use it as follows :
MyForm.Location = New Point(xLoc,yLoc)
'or
MyForm.Location = New Point(loc)
And one last thing , i really don't find your code fascinating enough to slide in a form .. You can easily use a Timer for that :
Dim Withevents tmr As New Forms.Timer
Dim myXLocation as integr
Private sub Btn_Click()
Tmr.start()
Private sub tmr_Tick()
myXloc= myXloc+ 1
MyForm.Location=New Point(myXloc,yloc)
If myXloc>= 190 Then 'change 190 to whatever u want :)
Tmr.Stop()
End if

Related

Making an auto typer from list view

I currently have everything working as it should except for one thing, right now I have the user type into a textbox, press the Add button and it inserts the text into the list view, when the autotyper starts it starts a timer tick with 6000 intervals and types the list but does not go back to the beginning of the list it repeats the last known phrase.
EX:
How can I make it start back over from the beginning if there is nothing left to be typed?
My code for the timer tick
intervalTimer_Tick.Start()
Dim SeprateLine As String
Dim Separator As Integer
If ListedItems.Contains(vbLf) Then
Separator = ListedItems.IndexOf(vbLf)
SeprateLine = ListedItems.Remove(Separator)
ListedItems = ListedItems.Substring(Separator + 1)
Else
SeprateLine = ListedItems
End If
SendKeys.Send(SeprateLine)
SendKeys.Send("{ENTER}")
If ListedItems <> "" Then
End If
End Sub
My code for button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each LVI As ListViewItem In ListView1.Items
If ListedItems = "" Then
ListedItems = LVI.Text
Else
ListedItems &= vbLf & LVI.Text
End If
Next
intervalTimer_Tick.Start()
End Sub
I think it's great you've started coding in VB.NET. You are almost there, but I want to give you a suggestion. Don't store your values on your user interface - store them in code off the UI thread. Using plain old objects to keep data makes it easier to write and read. Consider a List(Of string) to hold the items, and using a ListBox and DataSource to present the data. This allows for definite separation between what is UI and what is data.
Private ReadOnly items As New List(Of String)()
Private ReadOnly timer As New System.Threading.Timer(AddressOf autoType, Nothing, -1, -1)
Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
Dim s = InputBox("Add item", "Add", Nothing)
If s IsNot Nothing Then items.Add(s)
ListBox1.DataSource = Nothing
ListBox1.DataSource = items
End Sub
Private Sub RemoveButton_Click(sender As Object, e As EventArgs) Handles RemoveButton.Click
Dim si = ListBox1.SelectedIndex
If si >= 0 Then
items.RemoveAt(si)
ListBox1.DataSource = Nothing
ListBox1.DataSource = items
End If
End Sub
Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
' different buttons / handlers for different intervals
timer.Change(5000, 6000) ' 5s delay before first tick, 6s between subsequent ticks
End Sub
Private Sub autoType(state As Object)
' this ticks off the UI thread, so must Control.Invoke to run on the UI
Me.Invoke(Sub() SendKeys.Send(String.Join(vbLf, items)))
End Sub
To stop it, just change the timer again
timer.Change(-1, -1)

Creating handle in a Windows Form with a declared object as an array

Im trying to make a Connect 4 game just to practice some windows forms which im new to. What my code does is creates a grid of 7 x 6 regularly spaces blank PictureBox's. But since im creating them in the script and not using the form1 design windows i dont know how i would add Handles to them, especially since the PictureBox's are in an array. Any ideas?
Public Class Form1
Dim Grid(6, 5) As PictureBox
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Visible = False
Me.FormBorderStyle = FormBorderStyle.FixedSingle
For i As Integer = 0 To 6
For j As Integer = 0 To 5
Grid(i, j) = New PictureBox
Grid(i, j).BackColor = Color.LightGray
Grid(i, j).Size = New Size(90, 90)
Grid(i, j).Location = New Point((i * 100) + 10, (j * 100) + 10)
Grid(i, j).Visible = True
Controls.Add(Grid(i, j))
Next
Next
End Sub
Private Sub Grid_MouseHover(sender As Object, e As EventArgs) Handles Grid(x, y).MouseHover 'Doesnt work
'Run depending on which picturebox in array
End Sub
End Class
I can get an error which is "Handles clause requires a WithEvents variable defined in the containing type or one of its base types."
One possible way would be to set the .Tag property using the coordinates -
add something like into your For..Next loop
Grid(i, j).Tag = i.ToString & j.ToString
and use
AddHandler Grid(i, j).MouseHover, AddressOf Grid_MouseHover
and add this after the one above.
Then, change the first line of your MouseHover Sub to
Private Sub Grid_MouseHover(sender As Object, e As EventArgs)
with no handler on the end.
Finally, change the type of the sender to a PictureBox
Private Sub Grid_MouseHover(sender As Object, e As EventArgs)
Dim Pbox As PictureBox = CType(sender, PictureBox)
Dim i As Integer = Integer.Parse(Pbox.Tag.ToString(0))
Dim j As Integer = Integer.Parse(Pbox.Tag.ToString(1))
End Sub
To access the Picturebox and its properties, just use PBox and if you need the coordinates, use i and j

Labels don't redraw on Form.Refresh()

I have a form on which in the Paint event some labels with some information are drawn inside a panel - this works fine. However I would like to have the text on the labels being changed depending on the value of a Trackbar that is placed on the same form. This is the Trackbar-Scroll Event which should refresh the whole form:
Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
Me.Refresh()
End Sub
And this is the code that draws the labels on the form:
Public Sub Form_Paint(sender As Object, e As PaintEventArgs)
For i = 0 To 10
Dim tb As New Label
tb.Name = "tb" & CStr(i)
If Me.TrackBar1.Value = 1 Then tb.Text = "sometext"
If Me.TrackBar1.Value = 0 Then tb.Text = "anothertext"
tb.Location = New Point(i, i * 2)
Me.Panel1.Controls.Add(tb)
Next
End Sub
However no matter in what state the trackbar is the text displayed in the labels is alaways "anothertext". The Paint event is triggered as far as I can tell when I change the value of the trackbar but how can I also force the labels to update?
Just add the labels once. Separate the creating and changing logic into two methods
Private prefix As String = "tb"
Private factor As Integer = 10
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
addLabels()
changeLabels()
End Sub
Private Sub addLabels()
For i = 0 To 10
Dim tb As New Label()
tb.Name = prefix & CStr(i)
tb.Location = New Point(factor * i, factor * i * 2)
Me.Panel1.Controls.Add(tb)
Next
End Sub
Private Sub changeLabels()
For i = 0 To 10
Dim tb As Label = CType(Panel1.Controls(prefix & CStr(i)), Label)
If Me.TrackBar1.Value = 1 Then tb.Text = "sometext"
If Me.TrackBar1.Value = 0 Then tb.Text = "anothertext"
Next
End Sub
Now, in TrackBar1_Scroll, you can just change them (instead of recreating them)
Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
changeLabels()
End Sub
Since the label value depends on the TrackBar value, there is no reason to update them in Paint, which happens more frequently than the TrackBar is updated.
Adding new Labels and removing old Labels in Paint seems like a lot of extra processing.
I believe you need to set the LargeChange property of the TrackBar as a Scroll Event is considered a large change, but LargeChange defaults to 0, thus when you scroll the Value is only increasing/decreasing by 0, Leaving it at 0

if the file not exits then return no error vb

I have start this application every things its work fine but i have a small bug but i can not find the solution to solve the error.
i have debug it and the error its because the file not exist
is there any way to me to populate my datagridview with all *.gif images From a directory and the check if its null or some thing like that.
What i mean is is there any way to my to populate all gif images found on the chose Directory?
in fact i have all ready try like this but i get one error "Provided column already belongs to the DataGridView control.
Well finaly i have found a solution to load all images from a directory to a datagridview programmatic
Here Is The Working Code
Public Class Form5
Private Sub addBtn_Click(sender As Object, e As EventArgs) Handles addBtn.Click
'Populate()
ShowImages()
End Sub
'CLEAR DATAGRIDVIEW
Private Sub clearBtn_Click(sender As Object, e As EventArgs) Handles clearBtn.Click
DataGridView1.Rows.Clear()
End Sub
'WHEN AN IMAGE IS CLICKED
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
MessageBox.Show("You Clicked Image At Col: " + e.ColumnIndex.ToString() + " Row: " + e.RowIndex.ToString())
End Sub
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub ShowImages()
Dim directory As New System.IO.DirectoryInfo("C:\avitogifconverter\")
If directory.Exists Then
Dim pngFiles() As System.IO.FileInfo = directory.GetFiles("*.gif")
For Each pngFile As System.IO.FileInfo In pngFiles
If pngFile.Exists Then
Dim image = System.Drawing.Image.FromFile(pngFile.FullName)
Using image
Dim count = 1
' do something with the image like show in picture box
'CONSTRUCT IMG COLUMN
Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
imgCol.HeaderText = "Photo"
imgCol.Name = "Col 1"
DataGridView1.Columns.Add(imgCol)
'CONSTRUCT ROWS
'FIRST ROW
Dim img As Image = System.Drawing.Image.FromFile(pngFile.FullName)
Dim row As Object() = New Object() {img, img, img}
DataGridView1.Rows.Add(row)
End Using
End If
Next
End If
End Sub
End Class
Using Directory.EnumerateFiles, you could do something like this:
Dim row = New List(Of Image)(3)
For Each filename In Directory.EnumerateFiles("C:\avitogifconverter", "*.gif")
row.Add(Image.FromFile(filename))
If row.Count = 3 Then
DataGridView1.Rows.Add(row.ToArray())
row.Clear()
End If
Next
If row.Count > 0 Then
DataGridView1.Rows.Add(row.ToArray())
row.Clear()
End If

(VB) Suggestions with implementing a player shoot event

I'm currently working on a game in Visual Basic similar to an arcade shooter. The player moves their ship left and right across the screen using the arrow keys, while they 'shoot' using the spacebar. Problem is, I'm not sure where to place the bullet's movement so it will constantly move (not just spawn on a key-down event) and be updated by the Render() function. Any help or suggestions would be greatly appreciated.
My current code is displayed below; it's my first time using a game loop, so apologies if anything's misused.
Public Class frmMain
'Diming drawing surface & controls
Dim g, bbg As Graphics
Dim backBuff As Bitmap
Dim keys(256) As Boolean
Dim clientWidth, clientHeight As Integer
Dim timer As Stopwatch
Dim interval, startTick As Long
'Diming playerShip
Dim playerSize As Long = 64
Dim playerShip As New Rectangle(180, 430, playerSize, playerSize)
Dim playerLoc As New Point(playerShip.Location)
Dim playerSpr As Image = My.Resources.sprPlayer
Dim playerSpeed As Long
'Diming playerBullet
Dim playerBulletWidth As Long = 9
Dim playerBulletHeight As Long = 20
Dim playerBullet As New Rectangle(playerLoc.X, playerLoc.Y - 20, playerBulletWidth, playerBulletHeight)
Dim playerBulletLoc As New Point(playerBullet.Location)
Dim playerBulletSpr As Image = My.Resources.sprPlayerBullet
Dim playerBulletSpeed As Long
Dim playerShoot As Boolean = False
Public Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Configuring specific properties of the form
Me.DoubleBuffered = True
Me.MaximizeBox = False
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.Fixed3D
'Me.BackColor = Color.Black
'configuring timer controls
interval = 16
timer = New Stopwatch()
'Assigning values to empty variables
clientWidth = 450
clientHeight = 550
playerSpeed = 5
playerBulletSpeed = 5
'Configuring drawing surface
g = Me.CreateGraphics
backBuff = New Bitmap(clientWidth, clientHeight, Imaging.PixelFormat.Format32bppPArgb)
bbg = Graphics.FromImage(backBuff)
'Initially draw playerShip
bbg.DrawImage(playerSpr, playerShip)
'bbg.DrawImage(playerBulletSpr, playerBullet)
End Sub
Private Sub frmMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
keys(e.KeyCode) = True
End Sub
Private Sub frmMain_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
keys(e.KeyCode) = False
End Sub
Private Sub frmMain_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
GameLoop()
End Sub
Private Sub GameLoop()
timer.Start()
Do While (Me.Created)
startTick = timer.ElapsedMilliseconds
GameLogic()
Render()
Application.DoEvents()
'Allows game to run at constant speed on different machines
Do While timer.ElapsedMilliseconds - startTick < interval
Loop
Loop
End Sub
Private Sub GameLogic()
'Spawning, movement & collision
Dim keyPressed As Boolean = False
'playerShip movement & shooting
'Checks for no collision with form's right wall
If Not playerShip.Location.X + playerSpeed > clientWidth - playerShip.Width - playerSpeed Then
'Move playerShip right (right arrow)
If keys(39) Then
playerLoc = New Point(playerShip.Location.X + playerSpeed, playerShip.Location.Y)
playerShip.Location = playerLoc
keyPressed = True
End If
End If
'Checks for no collision with form's left wall
If Not playerShip.Location.X - playerSpeed < 0 Then
'Move playerShip left (left arrow)
If keys(37) Then
playerLoc = New Point(playerShip.Location.X - playerSpeed, playerShip.Location.Y)
playerShip.Location = playerLoc
keyPressed = True
End If
End If
'Launch bullet (space-bar)
If keys(32) Then
playerShoot = True
keyPressed = True
PlayerShipShoot()
End If
End Sub
Private Sub PlayerShipShoot()
'Add bullet activity here... maybe
End Sub
Private Sub Render()
'Drawing playerShip & playerBullet
bbg.DrawImage(playerSpr, playerShip)
If playerShoot = True Then
bbg.DrawImage(playerBulletSpr, playerBullet)
End If
'Drawing backBuff to the form
g.DrawImage(backBuff, 0, 0)
bbg.Clear(Color.Silver)
End Sub
End Class
Thanks.