Process.Start open too many multiple windows - vb.net

I started to program a couple of months ago and I'm having hard time with Process.Start command.
In the first form I've made a timer that can set a time and opens the program, that i defined it location in my TextBox box (another vb app that i built),
according to the time one enters and presses the "Set" button, when its time it opens the file that you choose.
For some reason it opens 10 multiple windows and on browsing for JPG file, it opens it only once, the multiple windows issues occurs only with .exe files.
Does anyone know the reason?
Here is my code so far:
Public Class startup
Dim iSetTime As Date
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If txtTMinute.Text <> String.Empty Then
Clipboard.SetText(txtTMinute.Text)
Else
Clipboard.Clear()
End If
txtTSecond.Clear()
txtTSecond.Paste()
If (Timer1.Enabled = True) Then
Timer1.Enabled = False
End If
iSetTime = txtTHour.Text + ":" + txtTMinute.Text + ":" + txtTSecond.Text
Timer1.Enabled = True
Label6.Text = "Timer not activated."
Me.Refresh()
System.Threading.Thread.Sleep(1000)
'MessageBox.Show("Activated Succesfully")
Label6.Text = "Timer Activated!"
Label6.ForeColor = Color.Green
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If (TimeOfDay = iSetTime) Then
Process.Start(TextBox1.Text)
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using ofd As New OpenFileDialog
ofd.Filter = "All files (*.*)|*.*"
ofd.Title = "Select File"
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Me.TextBox1.Text = ofd.FileName
End If
End Using
End Sub
End Class

You don't use enabled = true or false , you use timer.start or timer.stop , i don't know why are you even using a timer to do this? Anywho what's happening is the timer is continously looping through the code after little intervals because IT IS A TIMER and that's what it does until you stop it. If you really want to use a timer for this task then after this line Process.Start(TextBox1.Text) use this code: Timer1.Stop
By the way if you haven't changed the default interval of the timer then it would be set to 100 which is in milliseconds. it is equal to the same time as System.Threading.Thread.Sleep(100) and if you are stopping your timer after System.Threading.Thread.Sleep(1000) then it would've already looped the code: Process.Start(TextBox1.Text) 10 times because 1000/100 = 10

"When im browsing for JPG file, it opens it only once, only with exe
it multiple it."
I'm going to guess that it's trying to open anything you tell it to 10 times, the difference is that when you open an image, it is getting displayed in a single-instance program (like Preview, or Windows Image Viewer, or whatever it happens to be called), and then "reopened" in the same viewer instance 9 more times.
Set a breakpoint at this line:
Process.Start(TextBox1.Text)
When the breakpoint is encountered after running your application in the debugger, mouseover the two variables in the previous line, TimeOfDay and iSetTime in the IDE, and compare their values. I'd be willing to bet you're getting multiple True cases because of the implicit conversion between TimeOfDay's TimeSpan data format, and iSetTime as a Date.

Related

Play different MP3 files one by one in VB.Net 2019

I am creating a small forms application in VB.Net 2019 that will scan my harddrive for MP3 files and then play them in random order.
At this moment I scan my disk and load everything in two listboxes (one for the path, one for the filename because I also want to export in CSV). Somewhere in the future this data will go in a database with extra information so I can choose the genre of music I want to randomly play at that moment.
When I click my cmdRandom commandbutton, the first file starts to play but when I want to continue with the next random file, the file is searched and loaded into media player but doesn't start playing (I have to click "play" manually).
Here's my code:
Private Sub cmdRandom_Click(sender As Object, e As EventArgs) Handles cmdRandom.Click
intaantal = ListBox2.Items.Count
Randomize()
PlayMedia()
End Sub
Private Sub PlayMedia()
intNumber = CInt(Int((intAantal * Rnd()) + 1))
ListBox1.SelectedIndex = intNumber
ListBox2.SelectedIndex = intNumber
FileName = ListBox1.SelectedItem.ToString() + "\" + ListBox2.SelectedItem.ToString()
lblSongText.Text = FileName
' mPlayer.URL = ""
' mPlayer.Refresh()
' mPlayer.close()
' mPlayer.settings.autoStart = True
' mPlayer.settings.setMode("loop", True)
' mPlayer.Ctlcontrols.play()
mPlayer.URL = FileName
End Sub
Private Sub mPlayer_PlayStateChange(sender As Object, e As _WMPOCXEvents_PlayStateChangeEvent) Handles mPlayer.PlayStateChange
If mPlayer.playState = mPlayer.playState.wmppsMediaEnded Then
PlayMedia()
End If
End Sub
All items in PlayMedia() that are commented out have already been tested but don't work. I thought that adding mPlayer.Ctlcontrols.play() in the mPlayer_playStateChange () function in an else clause of the current if would work but that gives me a compilation error (seems to not be allowed in this event).
What am I doing wrong?
Found the sollution on the web after another search: (https://social.msdn.microsoft.com/Forums/sqlserver/en-US/31082234-7161-4446-a96e-32c0314dfe0f/actions-when-a-media-player-control-finished-playing?forum=vbgeneral). It all has to do with the time between the end of the first song and the loading of the next.
I added a timer and things are fixed now, I set the timer interval to 100.
Private Sub mPlayer_PlayStateChange(sender As Object, e As _WMPOCXEvents_PlayStateChangeEvent) Handles mPlayer.PlayStateChange
If mPlayer.playState = mPlayer.playState.wmppsMediaEnded Then
mPlayer.Ctlcontrols.stop()
Timer1.Start()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Stop()
PlayMedia()
End Sub

Can't get checking if file exists using textboxes to work

I've been racking my brain for days over this code and I just can't seem to get it working. I've researched and researched with no luck. I have four textboxes on my form. Two textboxes is a folder location and the other two textboxes are file locations. I'm trying to use a function that will return true or false telling if the files in the two textboxes exist or not. I don't see anything at all wrong with this code and it just won't work! I'm sure it's something simple I'm overlooking. Maybe someone else can spot it!
Private Function doesFileExist(folderPath, fileName) As Boolean
If IO.File.Exists(folderPath & "\" & fileName) Then
Return True
Else
Return False
End If
End Function
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If doesFileExist(txtCPU.Text, txtFileCPU.Text) And
doesFileExist(txtGPU.Text, txtFileGPU.Text) Then
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
Else
chkStart.Checked = False
chkStart.Text = "Start Monitor"
End If
Else
chkStart.Checked = False
MessageBox.Show("Please check directory & file locations!", "Error!", MessageBoxButtons.OK)
End if
End Sub
I want to mention that before I tried nested if statements on this I also tried to separate them both like so..
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If Not doesFileExist(txtCPU.Text, txtFileCPU.Text) And
Not doesFileExist(txtGPU.Text, txtFileGPU.Text) Then
chkStart.Checked = False
MessageBox.Show("Please check directory & file locations!", "Error!", MessageBoxButtons.OK)
Exit Sub
End If
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
Else
chkStart.Checked = False
chkStart.Text = "Start Monitor"
End If
End Sub
Both of these ways will show the messagebox if the application is ran with the checkbox checked on start up. Not only will it show the messagebox it also shows the messagebox twice! I've yet to figure that one out!
Your check file exists can be simplified... (It's been a while since I used VB so apologies for any syntax errors, I don't have an IDE to hand)
Function DoesFileExist(Folder as String, Filename As String) As Boolean
Return IO.File.Exists(IO.Path.Combine(Folder, Filename))
End Function
Re: Changing whether the "check" checkbox is set shouldn't perform the check itself - otherwise you only check when people click. (Incidentally, I'm guessing you're getting a message twice as code elsewhere ticks/unticks this checkbox, but it's only a guess).
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
PollTimer.Start()
Else
chkStart.Text = "Start Monitor"
PollTimer.Stop()
End if
End Sub
Finally... You need to define when your check will happen. Ideally, you'd want to use a FileSystemWatcher which will give you events when the file system changes, but you can also poll using a timer...
Private PollTimer As System.Timers.Timer
Then in your Form Main, do some initial timer setup...
...
PollTimer = New System.Timers.Timer()
PollTimer.Interval = 30000 ' Seconds
AddHandler PollTimer.Elapsed, AddressOf CheckExistsNow
PollTimer.Start()
...
And finally the code to run every time we want to make the check....
Sub CheckExistsNow(sender As Object, e As System.Timers.ElapsedEventArgs)
If Not DoesFileExist(txtGPU.Text, txtFileGPU.Text) Then
' Handle the missing file.
End if
End Sub

VB: Repeat the function evey x minutes?

I'm working with visual basic express 2010 to create a very simple application.
I know this is basic stuff but i need to know how to repeat the same function every X minute while the application is being left open.
This is all my code:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
My.Computer.Network.DownloadFile(
"http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
End Sub
End Class
could someone please advise on this issue?
EDIT:
This is my entire code now:
Public Class Form1
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
My.Computer.Network.DownloadFile(
"http://new.tse.ir/en/json/MarketWatch/enMarketWatch_1.xls", "C:/temp/enMarketWatch_1.xls", "", "", False, 60, True)
End Sub
End Class
in the properties panel of the timer, I set the Enabled to true and Interval to 60000.
when i run this code, I get file downloaded but 1 second later, the file gets deleted automatically and an error pops up in the visual basic saying the operation has timed out
I tried to change the directory and still happening.
any advise would be appreciated.
Add a timer to your form in the graphical designer.
Double click the timer to generate its tick event handler code in the code window.
Move the code you want to repeat into a sub
Private Sub DownloadFile()
My.Computer.Network.DownloadFile("http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
End Sub
Add the command below into your timer tick event handler
DownloadFile()
Change your form.load event to
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DownloadFile()
Timer1.Interval = x ' where x is the number of minutes*60000 because there are 60000 ticks in a minute
Timer1.Enabled = True
End Sub
The reason I've put your code into a separate sub is so that it is easily reusable in both the form.load handler and the timer.tick handler without having to write it again, and if in the future you need to change, for example the file path, you only need to remember to change it once.
Also I should add that, in the form.load handler I have included the DownloadFile method because, when the timer is enabled, it won't generate a tick until the interval has elapsed. Not at the beginning when the timer is enabled.
Also - as Plutonix suggested in comments below - If it is possible that the file to be downloaded will take longer to download than the length of the timer interval you should disable the timer in the DownloadFile sub and enable it again at the end of the sub. Like so :-
Private Sub DownloadFile()
Timer1.Enabled = False
My.Computer.Network.DownloadFile("http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
Timer1.Enabled = True
End Sub

VB.NET Upload to FTP with progressbar

I relise there is so many other questions out there regarding the progressbar, though I've looked through them "all" and can not find one that works.
I am trying to upload c:\screenshot.png to my ftp with a progress bar and a msgbox once finished.
Could someone provide a working example for me?
Thankyou
Edit heres the code I tried. Uploading works, though the progress bar dosent.
Sub UpdateProgressBar(ByVal sender As Object, ByVal e As UploadProgressChangedEventArgs)
If ProgressBar1.InvokeRequired Then
ProgressBar1.Invoke(New UploadProgressChangedEventHandler(AddressOf UpdateProgressBar), sender, e)
Exit Sub
End If
ProgressBar1.Value = CInt(ProgressBar1.Minimum + _
((ProgressBar1.Maximum - ProgressBar1.Minimum) * _
e.ProgressPercentage) / 100)
End Sub
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
Label16.Text = "Uploading now..."
Label16.Update()
Dim client As New System.Net.WebClient()
AddHandler client.UploadProgressChanged, AddressOf UpdateProgressBar
With client
.Credentials = New NetworkCredential( _
"damon#slimar.eu", "mine123!")
.UploadFile("ftp://slimar.eu/screenshot.png", "C:\screenshot.png")
End With
Label16.Text = "Done!"
Label16.Update()
End Sub
Progress bar has minValue,Max value, StepValue which is used to perform a step and Value to setup arbitray value.When you uploading a file or downloading you should be able to see via e paramenter total byte and actual byte trasmission.So you can setup Progress bar value and max value.
Also personally i invite you to use backgroundworker which :
Not Freeze GUI
Give you much controll on thread with no issue and no invoke needs
Make it more simple :)

Saving pdf document from webbrowser control

I'm navigating from webbrowser control to an url like this;
http://www.who.int/cancer/modules/Team%20building.pdf
It's shown in webbrowser control. What I want to do is to download this pdf file to computer. But I tried many ways;
Dim filepath As String
filepath = "D:\temp1.pdf"
Dim client As WebClient = New WebClient()
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(WebBrowserEx1.Url, filepath)
This one downloads a pdf but there is nothing in the file.
Also tried with
objWebClient.DownloadFile()
nothing changed.
I tried to show a save or print dialog;
WebBrowserEx1.ShowSaveAsDialog()
WebBrowserEx1.ShowPrintDialog()
but they didnt show any dialog. Maybe the last one is because it doesnt wait to load the the pdf into webbrowser completely.
When I try html files there is no problem to dowload, but in this .pdf file, I think I didn't manage to wait the file to be loaded as pdf into browser. This function(s);
Private Sub WaitForPageLoad(ByVal adimno As String)
If adimno = "1" Then
AddHandler WebBrowserEx1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
While Not pageReady
Application.DoEvents()
End While
pageReady = False
End If
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If WebBrowserEx1.ReadyState = WebBrowserReadyState.Complete Then
pageReady = True
RemoveHandler WebBrowserEx1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End If
End Sub
are not working for this situation. I mean it gets into infinite loop.
So anyone knows how to wait this to load pdf then save into computer.
you could test the URL when document completed fires and if its .pdf, then do the following then navigate back, for example.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowserEx1.Navigate("http://www.who.int/cancer/modules/Team%20building.pdf")
End Sub
Private Sub WebBrowserEx1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowserEx1.DocumentCompleted
If WebBrowserEx1.Url.ToString.Contains(".pdf") Then
Using webClient = New WebClient()
Dim bytes = webClient.DownloadData(WebBrowserEx1.Url.ToString) 'again variable here
File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.pdf"), bytes) 'save to desktop or specialfolder. to list all the readily available user folders
End Using
'WebBrowserEx1.goback() 'could send browser back a page as well
End If
End Sub
You will need to make the filename "TEST" as a variable instead of a static string or else you will overwrite the same file each time. Perhaps:
WebBrowserEx1.DocumentTitle.ToString & ".pdf"
instead, which would save the file as pdf named by the webpage title. Only problem there is if the page contains illegal characters (that windows doesnt let you save with) it will throw an exception so that should be handled.