Constant updating of a form in vb - vb.net

Is there a way to constantly update a form? I have a game with 3 difficulties and you need a high score of atleast 5 to unlock the next difficulty, it works but for the difficulties to unlock you need to relaunch the application. Or i am guessing use a button to update the difficulties, This is the code i have on form load.
EHighScore = My.Computer.FileSystem.ReadAllText("EasyHighScore.txt")
MHighScore = My.Computer.FileSystem.ReadAllText("MediumHighScore.txt")
HHighScore = My.Computer.FileSystem.ReadAllText("HardHighScore.txt")
If EHighScore < 5 Then
MediumDifficulty.Enabled = False
MediumDifficulty.BackColor = Color.Gray
Else
MediumDifficulty.Enabled = True
MediumDifficulty.BackColor = Color.Black
End If
If MHighScore < 5 Then
HardDifficulty.Enabled = False
HardDifficulty.BackColor = Color.Gray
Else
HardDifficulty.Enabled = True
HardDifficulty.BackColor = Color.Black
End If
How would i make this run when the form opens when i close the end screen that displays the score the user got (plus highscore if they did beat the high score) I have tried to do MainMenu.Close() when opening the game but the same result happens as MainMenu.Hide()

You can create and manipulate the variables & use a timer tool to update changes of a form in real-time (set the interval to 1000ms).
For example, consider the following code:
Declaration:
Dim difficult As Boolean
Code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
difficult = True
End If
And the timer:
Private Sub Timer1_Tick(...) Handles Timer1.Tick
if difficult = True Then
' ...
End If
End Sub
It will become easier for you to handle real-time things.
Caution: Don't use this trick which requires a network. Otherwise, it'll make your program unresponsive.

Related

(VB.NET) Quick way for a Simple Splashscreen for WinForms [duplicate]

This question already has answers here:
How to create a Splash screen for VB.net program
(3 answers)
Closed 6 days ago.
My program took ~5-10 seconds to load and sometimes people using it would end up trying to open it again, which caused problems. I found a quick and easy way to make a "splashscreen" (in a sense) that pops up for a set amount of time immediately on execution. I found that the first order of events in a WinForm EXE loading was Handle Created. The answer is not a true splashscreen, but for a couple lines of code that can be easily added to a project, I think some people will like it.
The below code will show a MessageBox immediately on running the EXE and closes after 10 seconds.
Imports System.Threading
Private Sub Control1_HandleCreated(ByVal sender As Object, ByVal e As EventArgs) Handles Me.HandleCreated
Dim SplashScreen As New Thread(
Sub()
CreateObject("WScript.Shell").Popup("Program Initializing, Please Wait...",10, "Setup Tool")
End Sub)
SplashScreen.Start()
End Sub
I use Threading so that the MessageBox will not freeze the code and the program will open with or without the OK button being pressed. Doing a regular MessageBox.Show() will prevent any more code from running until the user clicks OK I have found.
The best way I have found to implement a splash screen which keeps the user informed via messages and/or a progress bar or animated wheel is the following.
Have a startup form eg Form1, and have it carry out all the tedious startup procedures which might cause any animated or progress bar graphic to get stalled in the event queue. Add a "BackgroundWorker" object to Form1 from the Toolbox and in my case I just named it BackgroundWorker1.
Before starting these routines, usually in the Form1_Load event, make a call to the BackgroundWorker.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
CallBackgroundWork()
StartRoutines() 'this is the heavy lifting routines to get the app working. Set the LoadingStatusflag (declared as a Global Variable"
to various values to tell the splashscreen to display different messages
Loadingstatus = 10 'triggers splashform to exit
CancelBackgroundWork()
End Sub
These are the other subs to support this
Sub CallBackgroundWork()
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.WorkerReportsProgress = True
' call this method to start your asynchronous Task.
BackgroundWorker1.RunWorkerAsync()
End Sub
Sub CancelBackgroundWork()
' to cancel the task, just call the BackgroundWorker1.CancelAsync method.
BackgroundWorker1.CancelAsync()
End Sub
Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'' The asynchronous task we want to perform goes here
FormSplash.Show()
End Sub
My splashscreen has some label controls and pictureboxes and the FormSplash_Load event runs a stopwatch loop of 40ms and loads a series of images (24 in total) of a spinning wheel. This keeps running while the splashscreen is active. By setting the global variable Loadingstatus to various values within different part of the loading sequence in Form1 it can trigger the loop routine to display different messages example shown. An easy way to communicate between threads as you can't directly access objects between threads The wheel keeps spinning no matter how intensive the load routine in Form1 as it is running in another thread. I used a stopwatch loop as starting a timer doesn't work for me - maybe an event queue issue in splash form.
Private Sub FormSplash_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Show()
Me.Opacity = 1 'show this form
'now start a loop that gets ended by other thread through variable Loadingstatus flag
Dim ggtimer As New Stopwatch, lastvalue As Integer, FProgPosition as integer
ggtimer.Start()
lastvalue = ggtimer.ElapsedMilliseconds
nextimage:
FProgPosition += 1
If FProgPosition = 24 Then FProgPosition = 1 'has 24 frames in the animated image
Do 'loop for 40 ms
If ggtimer.ElapsedMilliseconds - lastvalue > 40 Then
lastvalue = ggtimer.ElapsedMilliseconds
Exit Do
End If
Loop
PictureBoxProgress1.Image = FProgIMG(FProgPosition)
PictureBoxProgress1.Refresh()
If Loadingstatus = 10 Then GoTo endsplash
If Loadingstatus = 1 Then
If CoreTempRunning = False Then
Me.LabelCoreTemp.Text = "CoreTemp is NOT Running"
Me.LabelCoreTemp.ForeColor = Color.White
'insert cross picturebox
PictureBoxCoreTemp.Image = My.Resources.ResourceManager.GetObject("Cross24x24")
loaderrorflag2 = True
Else
Me.LabelCoreTemp.Text = "CoreTemp is Running"
Me.LabelCoreTemp.ForeColor = Color.White
'insert tick picturebox
PictureBoxCoreTemp.Image = My.Resources.ResourceManager.GetObject("Tick24x24")
loaderrorflag2 = False
End If
Me.PictureBoxCoreTemp.Visible = True
Me.PictureBoxCoreTemp.Refresh()
Me.LabelCoreTemp.Left = Me.Width * 2 / 3 - Me.LabelCoreTemp.Width
Me.LabelCoreTemp.Refresh()
GoTo nextimage
endsplash:
ggtimer.Stop()
Me.Opacity = 0.01
Me.Hide()
End Sub

Infinite loop is causing the form to not show up vb

I have an infinite loop in this sub because I want the program to keep testing this process to see if the variable has changed. When I run the program in the debugger, nothing shows up, including the form however when I removed the infinite loop from the program, the form showed up again. Does anyone know why this is happening? I should also mention I've tried a DO LOOP as well. Can anyone help?
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim greenCount As Integer
Dim looptest As Boolean = True
While looptest = True
For Each control In Me.Controls.OfType(Of Button)
If control.BackColor = Color.Lime Then
greenCount += 1
End If
Next
txtFielder.Text = greenCount.ToString
End While
End Sub
You need to get rid of all that code regardless. Depending on how you're changing the BackColor of those Buttons in the first place, updating the lime count might be best done there. Otherwise, you should be handling the appropriate event, e.g.
Private limeButtonCount As Integer = 0
Private Sub Buttons_BackColorChanged(sender As Object, e As EventArgs) Handles Button3.BackColorChanged,
Button2.BackColorChanged,
Button1.BackColorChanged
If DirectCast(sender, Button).BackColor = Color.Lime Then
limeButtonCount += 1
Else
limeButtonCount -= 1
End If
TextBox1.Text = limeButtonCount.ToString()
End Sub
Note that this code assumes that there are only two possible BackColor values and that all Buttons are not lime by default. If your scenario is a bit more complex than that then you may need to change a code a little, e.g.
Private limeButtonCount As Integer = 0
Private Sub Buttons_BackColorChanged(sender As Object, e As EventArgs) Handles Button3.BackColorChanged,
Button2.BackColorChanged,
Button1.BackColorChanged
limeButtonCount = Controls.OfType(Of Button)().Count(Function(b) b.BackColor = Color.Lime)
TextBox1.Text = limeButtonCount.ToString()
End Sub
Form.Load occurs before a form is displayed for the first time.
This means that you'll never see your form as long as you loop in this event. You probably want to use the Shown event instead.

Dynamically updating a progress bar in VB

Hello I am a novice / mediocre VB programmer and I made a timer that simply need to update it self every second.
I started having doubts about weather or not it was working so I applied a msg box to my timers code it went off every second updating it self but the progress bar wont? why?
Dim power As PowerStatus = SystemInformation.PowerStatus
Dim percent As Single = power.BatteryLifePercent
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
ProgressBar1.Value = percent * 100
Label1.Text = percent * 100
End Sub
I have a power status and percent that takes the status and turn into a usable percentage then the progress bar uses that percentage but isnt updating like the msgBOX does why?
Well, your timer is probably working well and all, but you don't show where/how you get the updated value of SystemInformation.PowerStatus.BatteryLifePercent.
Maybe you're doing this somewhere else in your code, but as it is posted, you're always displaying the same value, so of course the progressbar is never going to change.
From what I can see from your question, everything should be working ok but I cant see that you have added Timer1.Interval = 1000 however you may have but this with the designer and not the coding side, however nevertheless here is how I did this project so you could see my working example just so you can be sure, If you have any problems let me know and i will do my best to help you out :)
Public Class Form1
Dim Timer1 As New Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
Timer1.Interval = 1000
AddHandler Timer1.Tick, AddressOf Timer1_Tick
Timer1.Start()
End Sub
Private Sub Timer1_Tick()
Dim POWER As PowerStatus = SystemInformation.PowerStatus
Dim PERCENT As Single = POWER.BatteryLifePercent
Dim ONCHARGE As PowerStatus = SystemInformation.PowerStatus
ProgressBar1.Value = PERCENT * 100
Label1.Text = "Power Remaining: " & PERCENT * 100 & "%"
If ONCHARGE.PowerLineStatus = PowerLineStatus.Online Then
Label2.Text = "Currently: Charging"
Else
Label2.Text = "Currently: Not Charging"
End If
End Sub
End Class
I added a Progressbar and two labels to the form, one of which is the computer battery and another of which will tell the user if the cable is unplugged in or not, i know you didnt ask for the cable status but i added it just incase you needed it :)
Happy Coding

changing calculate button to restart button after clicked

Is there any way to change a button to another button while running the program, i.e when the user clicks a button called "display", it calculates the results, then "display" turns into "Restart?" and if the user clicks that it restarts the program? I would like to change btnDisplay to btnRestart:
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
' displays a student's grade
Double.TryParse(txtEarned.Text, dblEarned)
For Each minimum As Double In dblMinimumPoints
If dblEarned >= minimum Then
lblGrade.Text = strGrade(gradeIndex)
gradeIndex += 1
End If
Next
txtEarned.ReadOnly = False
btnDisplay.Enabled = False
End Sub
I suppose there are multiple ways to do this. One is to have two buttons, btnDisplay and btnRestart, each with desired Text, that are laid on top of each other in the form designer. Alternate which one is visible when they are clicked.
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
' displays a student's grade
Double.TryParse(txtEarned.Text, dblEarned)
For Each minimum As Double In dblMinimumPoints
If dblEarned >= minimum Then
lblGrade.Text = strGrade(gradeIndex)
gradeIndex += 1
End If
Next
txtEarned.ReadOnly = False
btnDisplay.Visible = False
btnReset.Visible = True
End Sub
I'm not sure what you mean by saying that btnRestart will "restart the program", but presumably in its click event you would likewise hide it and make btnDisplay visible again.
(Also you might want to add some Try...Finally error handling in these events, so that even if something goes wrong, you can be sure the Visible lines will be executed.)
In your handler onclick and add a select case based on the .text attribute, then if the text is display update it it to restart, if it is restart then add a goto to where you want the script to start from on restart.
EDIT, below I have added the codetorun as a function which is probably a better solution than goto:
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Select Case btnDisplay.Text
Case "Submit"
codeiwanttorun()
btnDisplay.Text = "Restart"
Case "Restart"
codeiwanttorun()
End Select
End Sub
Private Function codeiwanttorun()
Double.TryParse(txtEarned.Text, dblEarned)
For Each minimum As Double In dblMinimumPoints
If dblEarned >= minimum Then
lblGrade.Text = strGrade(gradeIndex)
gradeIndex += 1
End If
Next
End Function

Play a sound in vb

Okay, so I have nearly perfected a game called lucky 7 using visual studio 2010. I want to play a sound when I have won the game (got 7 on one of the three slots). Here is the code:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
For i = 0 To 2
slots(i) = rand.Next(10)
Next
Label1.Text = (slots(0).ToString)
Label2.Text = (slots(1).ToString)
Label3.Text = (slots(2).ToString)
If slots(0) = 7 Or slots(1) = 7 Or slots(2) = 7 Then
score = score + 100 'REM 10 points for each win
Label4.Text = (score.ToString)
PictureBox1.Visible = True 'REM If you have a PictureBox
PlaySound "C:\WINDOWS\MEDIA\TADA.WAV",
Else
PictureBox1.Visible = False
End If
If score = 500 Then
MsgBox("You Scored 500 Points!", vbInformation)
End If
End Sub
Thing is, I get an error on the 'playsound' statement and I really want to play that sound when the player wins the game!
I also tried to create a reset button, which sets the score and all three slots back to 0, but when I click it, nothing happens. Here is the code for the reset button:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
score = 0
PictureBox1.Visible = False
End Sub
Try using My.Computer.Audio.Play
Have you walked through the code to make sure nothing is happening on the button click event? Clicking to the far left of the line "score = 0" will set a break-point. This will pause the code when you run it. You can hover over the variable score, and it will show it's value. Pressing [F8] will execute it, and you can hover over it and see that it's changed.
From your reset button event, your score is reset to 0 but not the text. No change to the text of your 3 slots as well.
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Label1.Text = "0"
Label2.Text = "0"
Label3.Text = "0"
Label4.Text = "0"
score = 0
PictureBox1.Visible = False
End Sub
As someone mentioned the sound files may not appear on every computer. You should look into using the system beep sound which can be modified to make some weird chimes. I had a lot of fun with it...
As for your reset button... You haven't coded the labels text to reset. I'm guessing you only want a visual change, as the values will still be changed when you play again. However being a reset button i guess you may want to reset each labels text to string.empty or something.
You should try this to play a .wav sound file:
My.Computer.Audio.Play("C:\WINDOWS\MEDIA\TADA.WAV",AudioPlayMode.Background)