Pausing & Resuming in Media Player - wpf

Currently im building a media player in Wpf VB.net. Im Stuck at play and pause button. It can pause but once i click play, the song started from beginning.I want it to resume from where i pause. Need your help guys.Below is my code
Private Sub btnPlay_Click(sender As Object, e As RoutedEventArgs) Handles btnPlay.Click
mplayer.Open(New Uri(ImagePath & iPodList.SelectedValue, UriKind.RelativeOrAbsolute))
If btnPlay.Content = "Play" Then
mplayer.Play()
btnPlay.Content = "Pause"
ElseIf btnPlay.Content = "Pause" Then
mplayer.Pause()
btnPlay.Content = "Play"
End If
End Sub

Whatever mplayer is, I would assume that the fact that you call Open on it every time you click that Button would be the issue. If you want to pause and resume what is already playing then don't open something new.

Related

Close a file before invoking File.WriteAllBytes?

I have an Windows Forms application that stores PDF files as byte arrays in the database (not my first choice, but I didn't set up the database...). I want the user to be able to view one of these stored files by clicking a basic "view document" button.
With the code I have right now, the bytes are written to a file on disk, then opened using an external process (default PDF reader on user's machine). The problem is that if they click the "view document" button again before closing the file, an exception is thrown because an open file can't be overwritten.
Since I've used Process.Start() to open the file, I've tried various ways of killing the process, but I can't find a way to get the process by the filename (rather than whatever reader program opens the file, which is unknown to the app).
The relevant code inside the click handler is basic:
File.WriteAllBytes("document.pdf", PDFBytes)
Process.Start("document.pdf")
(PDFBytes is the byte array, document.pdf is just the path I'm using to store the file before it's opened. It'll get overwritten every time the user clicks the "view document" button, which is fine).
Expected result: user can click "view document" to open the PDF multiple times, and the file will close and reopen with each subsequent click without problems.
Actual result: first click opens the document just fine, next click (without closing the file first) throws "System.IO.IOException: The requested operation cannot be performed on a file with a user-mapped section open."
If I am understanding the issue this might help
Dim tempFileName As String
Dim pathToFile As String
Try
tempFileName = IO.Path.GetTempFileName
pathToFile = IO.Path.ChangeExtension(tempFileName, "pdf")
IO.File.WriteAllBytes(pathToFile, PDFBytes)
Process.Start(pathToFile)
IO.File.Delete(tempFileName)
Catch ex As Exception
'todo
End Try
edit:
delete old pdfs
Dim tdir As String = IO.Path.GetTempPath
Dim di As New IO.DirectoryInfo(tdir)
Dim fis() As IO.FileSystemInfo = di.GetFileSystemInfos
Dim ctDel As Integer = 0
For Each fi As IO.FileSystemInfo In fis
If fi.CreationTime.AddDays(28) < Date.Now Then 'older than 28 days
Try
If fi.Extension = ".pdf" Then
IO.File.Delete(fi.FullName)
ctDel += 1
End If
Catch ex As Exception
'todo
' Stop
End Try
End If
Next

Making code execute in Sync VB.net | WPF

I am designing an application in WPF where if you click on a button it will load that application. Example, you press spotify it will load spotify.
Thing is, sometimes there is delays for when the application (Spotify) opens which is normal! So I am adding a loading section so it will hide the logo, and my loading panel will appear in its place!
Works and looks great but I have an issue! Some reason, the gui wont update with my loading but instead my application loads first and then a few moments after it will update GUI with my loading bar. I want it so as soon as a user presses the button then they will instantly see this loading appear and then will disappear once application has successfully loaded in.
Button code:
Dim syncTask As New Task(Of Long)(Function()
MPanel_Spotify.Visibility = Windows.Visibility.Hidden 'Hide Button Info
LoadPanel_Spotify.Visibility = Windows.Visibility.Visible 'Show Load
Dim LPro = Process.Start(SpotifyGlobalDir)
Console.WriteLine("Loading App")
LPro.WaitForInputIdle()
Dim ProcessCheck = Process.GetProcessesByName("Spotify")
Do
Thread.Sleep(2000)
Loop Until ProcessCheck.Count > 0
Console.WriteLine("App loaded")
' LoadPanel_Spotify.Visibility = Windows.Visibility.Hidden 'Hide Load
'MPanel_Spotify.Visibility = Windows.Visibility.Visible 'Show Button Info
Return True
End Function)
syncTask.RunSynchronously()
I think I might need some multithreading? But if i do that i get errors as I need to invoke the visibility changes which I dont know how to do?
Try to call Process.Start and Thread.Sleep on background thread but set the Visibility properties of the elements on the UI thread:
MPanel_Spotify.Visibility = Windows.Visibility.Hidden 'Hide Button Info
LoadPanel_Spotify.Visibility = Windows.Visibility.Visible 'Show Load
Task.Run(Sub()
Dim LPro = Process.Start(SpotifyGlobalDir)
Console.WriteLine("Loading App")
LPro.WaitForInputIdle()
Dim ProcessCheck = Process.GetProcessesByName("Spotify")
Do
Thread.Sleep(2000)
Loop Until ProcessCheck.Count > 0
End Sub) _
.ContinueWith(Sub(t)
Console.WriteLine("App loaded")
LoadPanel_Spotify.Visibility = Windows.Visibility.Hidden 'Hide Load
MPanel_Spotify.Visibility = Windows.Visibility.Visible 'Show Button Info
End Sub, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext())
The UI thread cannot both display the controls and sleep at the same time. A single thread can only do one single thing at a time.

Adding a DocumentWindow to a DocumentTabStrip causes the application to hang indefinitely

I have a Winforms application with a primary form that contains (among other things) a Telerik DocumentTabStrip. These tabs are used to hold user controls or web pages (via a web browser control). It has worked fine for quite a while, but I'm running into an issue now.
I recently switched the web browser control from the built-in .NET web browser based on IE to CefSharp. Since doing so, I've noticed that occasionally when trying to add the DocumentWindow to the DocumentTabStrip, the call will hang indefinitely (in debug) or crash outright (running the app normally). This only appears to happen when opening a DocumentWindow that contains the browser control, not any other user controls. The actual call itself is below.
I'm at a bit of a loss as to how to even begin to debug this, since there's no error that gets received - it just hangs inside the Controls.Add() method indefinitely. Any advice would be appreciated.
Private dts As New Telerik.WinControls.UI.Docking.DocumentTabStrip
Try
dts.InvokeIfRequired(Sub()
Dim docWindow As Telerik.WinControls.UI.Docking.DocumentWindow = Nothing
Dim ctrl As ucBaseControl = Nothing
Dim browser As ucBrowser = Nothing
Dim isBrowser As Boolean = False
docWindow = New Telerik.WinControls.UI.Docking.DocumentWindow
docWindow.BackColor = Color.FromArgb(89, 89, 89)
'Do various stuff to determine the type of control to load (ctrl or browser), then setup the applicable control
If isBrowser Then
'Place the browser into the Document Window.
If Not IsNothing(browser) Then
browser.Dock = DockStyle.Fill
docWindow.Controls.Add(browser)
End If
Else
'Place the ctrl into the Document Window.
ctrl.Dock = DockStyle.Fill
docWindow.Controls.Add(ctrl)
End If
'Add the DocumentWindow to the DocumentTabStrip
' Ensure DockWindow not disposed due to lag in bringing up
If IsNothing(docWindow) OrElse docWindow.IsDisposed Then
Exit Sub
End If
Try
docWindow.Padding = New Padding(0)
dts.TabStripElement.Children(0).Children(1).Padding = New Padding(0)
dts.Controls.Add(docWindow) 'This is where the issue is. It only happens sporadically here.
Catch ex As Exception
'Code to log any exceptions here. In the problem described here, no exception is ever generated, though.
End Try
'Bring the control to the front and focus it, here...
End Sub)
Catch ex As Exception
'Error handling code here'
End Try
I'm assuming InvokeIfRequired is an extension method you've created for Controls. Note that if it relies on Invoke, that is a synchronous call, instead use BeginInvoke (see: What's the difference between Invoke() and BeginInvoke())
No exception was ever thrown because you were suffering from deadlock

WebBrowser Fails with MP3 URL

My application has a webbrowser control that works fine with most sites, but is having trouble with pages intended to play MP3s.
The code below sends the URLs to webViewer, my WebBrowser control. Regular pages work, however, one like this does not, and results in the browser displaying a white page with the "x" shown in the image at the top left. The page does load properly in Internet Explorer and displays a QuickTime player that plays the file.
Private Sub NavigateTo(ByVal webAddress As String)
Try
If String.IsNullOrEmpty(webAddress.Trim()) Then
MsgBox("This link is under construction...")
Return
Else
If webAddress.Contains("http://") = False Then webAddress = "http://" & webAddress
Dim navPage As New Uri(webAddress)
webViewer.Source = navPage
End If
Catch ex As Exception
MsgBox("The URL for this button is invalid. Please contact AzTech IT for help.", MsgBoxStyle.OkOnly, "Satellite Tablet Application")
ErrorHandler.Helpers.LogMessage(ex.Message)
End Try
End Sub
Is there a workaround for this issue?

VB.net GetProcess Options

I currently have the following code that runs an external Virtual Application(created with Cameyo), when the Run Button is clicked. I also have a Timer that checks ever second to see if the Process(virtual exe program) is still open. In theory the GetProcessByName should find the program listed in the Task Manager right? However it doesn't! I even tried using GetProcessByName to Kill the process (one another button clicked), but the processs is not killed.
Could it be because I virtualized the program that I want GetProcessByName to recognize? Therefore the name of the Task in the Task Manager is not correct?.
Example
The program started: SmartDefrag.virtual.exe
It runs
The Task Manager shows it as SmartDefrag.exe
Use GetProcessByName("SmartDefrag.exe") to Disable Run Button if process SmartDefrag.exe running.
Does not Disable Run Button.
Could I use TITLE OF PROCESS? Or will the PID be the same everytime the process opens? Any other options?
Code:
Private Sub SMDFRunAppMainButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles SMDFRunAppMainButton.Click
' LoadingSMDFMainButton.Visibility = Windows.Visibility.Visible
Dim downloadlocation As String = (currentpath & "\1stAidApps\SMDF\SmartDefrag.virtual.exe")
My.Settings.FileLoad = downloadlocation
Try 'Errors on Cancel
dp1Timer = New DispatcherTimer
dp1Timer.Interval = TimeSpan.FromMilliseconds(1000)
AddHandler dp1Timer.Tick, AddressOf TickMe1
dp1Timer.Start()
fileload = My.Settings.FileLoad
Process.Start(fileload)
Catch ex As Exception
MessageBox.Show("Failed to launch. Please try again.", "Launch Failed")
End Try
End Sub
Private Sub TickMe1()
Dim p() As Process
p = Process.GetProcessesByName("SmartDefrag.exe")
If p.Count > 0 Then
LoadingSMDFMainButton.Visibility = Windows.Visibility.Hidden
SMDFRunAppMainButton.IsEnabled = False
Else
SMDFRunAppMainButton.IsEnabled = True
End If
End Sub
GetProcessByName doesn't take the full path, but rather the "name" of the process. This will likely need to be GetProcessByName("SmartDefrag").
From the documentation for GetProcessByName:
The process name is a friendly name for the process, such as Outlook, that does not include the .exe extension or the path.

Resources