How to get value from ComboBox and TextBox into Argument line? - vb.net

I want to unzip a specific file with a external Program in VB.NET but, I don't know how to do that.
This is my attempt.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Process.Start("7z.exe","-e" Textbox1.Text + Combobox1.Text )
End Sub

Instead of using the 7z.exe use the DLL they provide.
Public Class ArchivationHandling
Private Declare Function SevenZip Lib "7-zip32.dll" (ByVal hwnd As Integer, ByVal strCmdLine As String, ByVal strOutput As String, ByVal dwSize As Integer) As Long
Private bJobCompleted As Boolean = False
Private Const ZIP_EXTENSION As String = ".zip"
Private Const SEVEN_ZIP_PAR As String = vbNullString
Private Function Decompress(ByVal strZipPath As String, ByVal strOutPut As String) As Boolean
Dim strZipComm As String = "x -o" & strOutPut & " " & strZipPath & ZIP_EXTENSION & " -hide"
Try
SevenZip(0, strZipComm, SEVEN_ZIP_PAR, 0)
bJobCompleted = True
Catch ex As Exception
Logger.WriteLogEntry(4, "Decompression failed for file: " & strZipPath & " " & ex.Message.ToString)
End Try
Return bJobCompleted
End Function
Public ReadOnly Property Decompression(ByVal strZipFilePath As String, ByVal strOutput As String) As Boolean
Get
Return Decompress(strZipFilePath, strOutput)
End Get
End Property
End Class
This is an example of what I use in one of my applications.
You just provide the input file and output.

Related

(VB.NET) Object reference not set to an instance of an object

This program works like this: User enters building name and number of floors, that gets validated and accepted. Then user enters rates for each floor until it goes through all floors, that data gets added to a listbox, then user enters a desired floor and it adds the rent and other info to another listbox lower down. As soon as I enter my number of floors and click on the button to save the info, the program runs into an error under btnEnterBuilding Click event where it says dblRates(intHowMany) = dblRent. The error is
"An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication5.exe
Additional information: Object reference not set to an instance of an object."
Any help would be greatly appreciated, thanks!
Option Explicit On
Option Strict On
Option Infer Off
Public Class Form1
Dim dblRates() As Double
Dim intHowMany As Integer = 0 'points to the next avail entry in the array
Private Function ValidateString(ByVal strText As String, strInput As String, strValue As String) As Boolean
If strText = Nothing Then
MessageBox.Show(strText & " Must Be Supplied", "Error")
Return False
Else
Return True
End If
End Function
Private Function ValidateInteger(ByVal strText As String,
ByVal strIn As String,
ByRef intValue As Integer,
ByVal intMinValue As Integer,
ByVal intMaxValue As Integer) As Boolean
If strIn = Nothing Then
MessageBox.Show(strText & " Must Be Supplied", "Error")
Return False
Else
If Integer.TryParse(strIn, intValue) = False Then
MessageBox.Show(strText & " Must Be A Whole Number", "Error")
Return False
Else
If intValue < intMinValue Or intValue > intMaxValue Then
MessageBox.Show("Outside of Number of " & strText & " Limits", "Error")
Return False
Else
Return True
End If
End If
End If
End Function
Private Function ValidateDouble(ByVal strText As String,
ByVal strDbl As String,
ByRef dblValue As Double,
ByVal dblMinValue As Double,
ByVal dblMaxValue As Double) As Boolean
If strDbl = Nothing Then
MessageBox.Show(strText & " Must Be Supplied", "Error")
Return False
Else
If Double.TryParse(strDbl, dblValue) = False Then
MessageBox.Show(strText & " Must Be A Whole Number", "Error")
Return False
Else
If dblValue < dblMinValue Or dblValue > dblMaxValue Then
MessageBox.Show("Outside of Number of " & strText & " Limits", "Error")
Return False
Else
Return True
End If
End If
End If
End Function
Private Sub Form1_Load(sender As Object,
e As EventArgs) Handles Me.Load
Me.grpBuilding.Enabled = True
Me.grpRents.Enabled = False
Me.grpDesiredFloor.Enabled = False
End Sub
Private Sub btnRents_Click(sender As Object,
e As EventArgs) _
Handles btnRents.Click
Dim strName, strFloors As String
Dim intFloors As Integer
strName = txtName.Text
strFloors = txtFloors.Text
intFloors = CInt(strFloors)
If ValidateString("Building name", Me.txtName.Text, strName) = True Then
If ValidateInteger("Number of floors", Me.txtFloors.Text, intFloors, 3, 20) = True Then
Me.grpBuilding.Enabled = False
Me.grpRents.Enabled = True
Me.grpDesiredFloor.Enabled = False
End If
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub btnEnterBuilding_Click(sender As Object,
e As EventArgs) _
Handles btnEnterBuilding.Click
Dim intFloors As Integer
Dim dblRent As Double
Dim strRent As String
strRent = txtRent.Text
dblRent = CDbl(strRent)
If ValidateDouble("Rent", Me.txtRent.Text, dblRent, 1000.0, 2500.0) = True Then
dblRates(intHowMany) = dblRent
Me.txtRent.Focus()
Me.txtRent.SelectAll()
Me.ListBox1.Items.Add("Floor No. " & intHowMany.ToString("N0") &
" -- Rent Is: " & dblRent.ToString("N$"))
If intHowMany < intFloors Then
intHowMany += 1
Else
Me.grpBuilding.Enabled = False
Me.grpRents.Enabled = False
Me.grpDesiredFloor.Enabled = True
End If
Else
Me.txtRent.Focus()
Me.txtRent.SelectAll()
End If
End Sub
Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
Dim intFloors, intFloor As Integer
Dim strName, strFloors As String
strName = txtName.Text
strFloors = txtFloors.Text
intFloors = CInt(strFloors)
If ValidateInteger("Desired Floor", Me.txtFloor.Text, intFloor, 3, 20) = False Then
MessageBox.Show("Please enter a valid floor number", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Me.lstDisplay.Items.Add("Building Name: " & strName & " # of Floors: " & intFloors.ToString)
Me.lstDisplay.Items.Add("Desired Floor: " & intFloor.ToString)
Me.lstDisplay.Items.Add(" Rent: " & intFloors.ToString)
End If
End Sub
End Class
You can't dim dblRates() as double like this without giving it initial values. You will need to dim dblRates(<some amount>) as Double and then redim it if necessary to add more values to it. Or you could Dim dblRates() as double = {0} but if you still want to add more values to the array, you will still need to redim it as the second options would just create an array of 1 element.

I have a class that I am using 4 times. Two of the Labels using the class work but when I add a new Label it does not work

The code was working and then suddenly stopped for the newer Labels that I have added to the form. It seems like the Timer code that subtracts the time and adds to the AccTimeStg is not being called. The ArrayTimer works the Prefix text changes just fine so that timer is working. So the First two Labels I have on the form do as they are coded to do. I thought that when a change was made to a class and then a build was done the changes were made to all the objects that were using that class. I tested that theory as well Being new to using classes, It worked that way. I just don't understand how the old Labels are not affected but newer ones are not working.
Here is the code
Option Strict On
Imports System.Text
Imports System.IO
Imports System.Collections.Generic
Public Class TimeLogLabel
Inherits Label
Private m_VaraibleToSet As Boolean
<System.ComponentModel.Category("Control")> _
Public Property VaraibleToSet() As Boolean
Get
Return m_VaraibleToSet
End Get
Set(ByVal value As Boolean)
m_VaraibleToSet = value
End Set
End Property
Private m_PrefixText As String = "Prefix Text"
<System.ComponentModel.Category("Control")> _
Public Property PrefixText() As String
Get
Return m_PrefixText
End Get
Set(ByVal value As String)
m_PrefixText = value
End Set
End Property
Public Class LogTime
Private m_EventName As String
Public Property EventName() As String
Get
Return m_EventName
End Get
Set(ByVal value As String)
m_EventName = value
End Set
End Property
Private m_StartT As String
Public Property StartT() As String
Get
Return m_StartT
End Get
Set(ByVal value As String)
m_StartT = value
End Set
End Property
Private m_StopT As String
Public Property StopT() As String
Get
Return m_StopT
End Get
Set(ByVal value As String)
m_StopT = value
End Set
End Property
Private m_TSpan As String
Public Property TSpan() As String
Get
Return m_TSpan
End Get
Set(ByVal value As String)
m_TSpan = value
End Set
End Property
Public Sub New( _
ByVal m_EventName As String, _
ByVal m_StartT As String, _
ByVal m_StopT As String, _
ByVal m_TSpan As String)
EventName = m_EventName
StartT = m_StartT
StopT = m_StopT
TSpan = m_TSpan
End Sub
End Class
'***********************
Private Timer As Timer
Private ArrayTimer As Timer
Public StartTime As Date
Public StopTime As Date
Public AccTimeStg As String
Public TimeArray(19) As String
Private Ons As Boolean
Public Sub New()
Timer = New Timer
Timer.Interval = 1
AddHandler Timer.Tick, AddressOf Timer_Tick
ArrayTimer = New Timer
ArrayTimer.Interval = 100
ArrayTimer.Enabled = True
AddHandler ArrayTimer.Tick, AddressOf ArrayTimer_Tick
End Sub
Public TimeList As List(Of LogTime) = New List(Of LogTime)
Dim EventId As Integer
Public Sub StartTimer()
If Ons = False Then
Ons = True
EventId = EventId + 1
StartTime = Now
AddLog(TimeArray, PrefixText & ": Start Time " & StartTime)
TimeList.Add(New LogTime(PrefixText & " " & EventId, "Start Time " & StartTime, "", ""))
Timer.Enabled = True
Timer.Start()
End If
End Sub
Public Sub StopTimer()
If Ons = True Then
Ons = False
EventId = EventId + 1
StopTime = Now
AddLog(TimeArray, PrefixText & ": Stop Time " & StopTime & " Up Time " & AccTimeStg)
TimeList.Add(New LogTime(PrefixText & " " & EventId, "", "Stop Time " & StopTime, " Up Time " & AccTimeStg))
Timer.Enabled = False
Timer.Stop()
End If
End Sub
Public Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Dim TimeSpan As TimeSpan = Now.Subtract(StartTime)
AccTimeStg = TimeSpan.Days & " : " & TimeSpan.Hours & " : " & TimeSpan.Minutes & " : " & TimeSpan.Seconds
End Sub
Private Sub ArrayTimer_Tick(ByVal sender As Object, ByVal e As EventArgs)
'''' Me.Text = String.Join("XX", TimeList)
' this is the normal Me.text
Me.Text = PrefixText & " " & AccTimeStg
End Sub
Private Sub AddLog(ByVal logAsArray() As String, ByVal newEntry As String)
For index As Integer = logAsArray.Length - 1 To 1 Step -1
logAsArray(index) = logAsArray(index - 1)
Next
logAsArray(0) = newEntry
End Sub
End Class
I have figured it out. With the help of #Ben N THX
Private WithEvents Timer As Timer
Private WithEvents ArrayTimer As Timer
was needed to use the handles
Public Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer.Tick

Vb.net Save data from datagridview to txt and load it

i'am new programmer and just studying about Visual Basic, and to complete my exams
The Data i have
Tool_1 screwdriver
Tool_2 screw
Tool_3 Magnet
And many more
i've create project, it have Data Grid View(two columns, Tools & Names) and two Button(btSave & btOpen)
i just try it with this code
Private Sub btSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btSave.Click
SaveGridData(DataGridView1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub btOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btOpen.Click
LoadGridData(DataGridView1, ThisFilename)
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, " "))
Next
End Sub
When i save the file it's no problem the txt file is ok, but when i want to load Text "Tool_1 Screwdriver" is not split but is in "Tools" Column
there is a solution to this ?
use this insetad of your loop in loadgriddata
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
dim str as string()
str=thisline.split(" ")
ThisGrid.Rows.Add(str(0),str(1))
Next
hope it helps.
Hey I struggled with this aswell, but I have some usefull code:
export listview:
System.IO.Directory.CreateDirectory("C:\RS Account Maker\Accounts" & "\")
SaveFileDialog1.ShowDialog()
Dim Path As String = SaveFileDialog1.FileName
Dim AllItems As String = ""
Try
For Each item As ListViewItem In ListView1.Items
AllItems = AllItems & item.Text & "#" & item.SubItems(1).Text & "#" & item.SubItems(2).Text & vbNewLine
Next
AllItems = AllItems.Trim
Catch ex As Exception
End Try
Try
If My.Computer.FileSystem.FileExists(Path) Then
My.Computer.FileSystem.DeleteFile(Path)
End If
My.Computer.FileSystem.WriteAllText(Path, AllItems, False)
Catch ex As Exception
MsgBox("Error" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Error ")
End Try
import listview:
OpenFileDialog1.ShowDialog()
Dim Path As String = OpenFileDialog1.FileName
Dim AllItems As String
Try
AllItems = My.Computer.FileSystem.ReadAllText(Path)
Dim ItemLines As New TextBox
ItemLines.Text = AllItems
For Each line As String In ItemLines.Lines
Dim a1() As String = line.Split("#")
Dim ItemName As String = a1(0)
Dim SubItem1 As String = a1(1)
Dim SubItem2 As String = a1(2)
Dim Item As New ListViewItem(ItemName)
Item.SubItems.Add(SubItem1)
Item.SubItems.Add(SubItem2)
ListView1.Items.AddRange(New ListViewItem() {Item})
Next
Catch ex As Exception
MsgBox("Error" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Error ")
End Try
The following line is wrong.
ThisGrid.Rows.Add(Split(THisLine, " "))
The above code was amended as follows.
Dim ThisFilename As String = Application.StartupPath & "\MyData.dat"
Private Sub butSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SaveGridData(Datagrid1, ThisFilename)
End Sub
Private Sub butLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
LoadGridData(Datagrid1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, ControlChars.Tab))
Next
End Sub

Beginner doing an OOP Project vb.net

Alright, so I have edited my code and now when I'm trying to run it I'm getting this error.
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "Holden 308" to type 'Integer' is not valid.
Additional information: Conversion from string "JD Catepillar Track" to type 'Integer' is not valid.
So both errors are happening in the HeavyStockItem class with the overloading New classes. Wondering if anyone can help me out with understanding why it's doing that.
Option Strict On
Public Class Form1
Dim StockItem1 As StockItem
Dim StockItem2 As CarEngine
Dim StockItem3 As CarEngine
Dim StockItem4 As StockItem
Dim StockItem5 As HeavyStockItem
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StockItem1 = New StockItem("Screwdriver Set", 42)
StockItem2 = New CarEngine(8025, "Madza B6T", 1252, 800, "Z4537298D")
'StockItem3 = New CarEngine("Holden 308", 958, 1104, "P74623854S")
StockItem4 = New StockItem(8002, "Trolley Jack", 127)
'StockItem5 = New HeavyStockItem("JD Catepillar Track", 3820, 2830)
End Sub
Private Sub btnListStock_Click(sender As Object, e As EventArgs) Handles btnListStock.Click
txtOutput.Clear()
ShowOutput(StockItem1)
ShowOutput(StockItem2)
'ShowOutput(StockItem3)
ShowOutput(StockItem4)
'ShowOutput(StockItem5)
End Sub
Public Sub ShowOutput(ByVal Output As StockItem)
txtOutput.Text &= Output.Print()
txtOutput.Text &= vbCrLf
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnd.Click
End
End Sub
End Class
Public Class StockItem
Friend CostPrice As Integer
Friend LastStockNumber As Integer
Friend StockNumber As Integer
Friend Description As String
Friend Shared LastStockItem As Integer = 10000
Overridable Function Print() As String
Dim Result As String = ""
Result &= "Stock No: " & StockNumber
Result &= vbCrLf
Result &= "Description: " & Description
Result &= vbCrLf
Result &= "Cost Price: " & CostPrice
Result &= vbCrLf
Return Result
End Function
Public Sub New(ByVal StockNumber As Integer, Description As String, ByVal CostPrice As Integer)
Me.New(Description, CostPrice)
Me.StockNumber = StockNumber
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer)
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
Me.Description = Description
Me.CostPrice = CostPrice
End Sub
Public Sub GetCostPrice()
End Sub
End Class
Public Class HeavyStockItem
Inherits Assessment3.StockItem
Friend Weight As Integer
Public Function GetWeight() As String
Return Me.GetWeight
End Function
Public Sub New(ByVal StockNumber As Integer, ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer)
MyBase.New(StockNumber, Description, CostPrice)
Me.Weight = Weight
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer)
MyBase.New(Description, CostPrice, Weight)'' Where the error is occurring
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
End Sub
End Class
Public Class CarEngine
Inherits Assessment3.HeavyStockItem
Friend EngineNumber As String
Overrides Function Print() As String
Dim Result As String = ""
Result &= "Stock No: " & StockNumber
Result &= vbCrLf
Result &= "Description: " & Description
Result &= vbCrLf
Result &= "Cost Price: " & CostPrice
Result &= vbCrLf
Result &= "Weight: " & Weight
Result &= vbCrLf
Result &= "Engine Number: " & EngineNumber
Result &= vbCrLf
Return Result
End Function
Public Sub New(ByVal StockNumber As Integer, ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer, ByVal EngineNumber As String)
MyBase.New(StockNumber, Description, CostPrice, Weight)
Me.EngineNumber = EngineNumber
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer, ByVal EngineNumber As String)
MyBase.New(Description, CostPrice, Weight)
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
End Sub
End Class
Any help provided would be great. Just thought it'd be easier to provide the full code instead of just putting only the little bits that I really needed, incase if people asked about the other parts of the code. Thanks for reading and providing help if you provided help.
Since your code was confusing to me I relied mostly on the exception.
It basically says that it cant convert the string into an integer. Here's something that could cause the same problem.
Dim Number As String = "10"
'Few Lines of code.
Number = 11
whats basically happening is that when you declare a variable as a string the value of it HAS to be in double quotes as you see when it was declared. Now then we try to change the value to 11 while adding no double quotes, therefor it thought you were changing it to an integer and gave the error.
I looked through the code and saw this, maybe this is causing it:
Me.Description = Description <--- No quotes!!!
I'm probably wrong though since i didn't really understand the code.

VB.Net playing mp3 at the same time

I've been wondering about this, I have tried multiple suggestions I have got from different sites. I have my code here but it's not working.
Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" _
(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal _
uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
Private Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim fileName As String
FileName = Chr(34) & (Button1.Text) & Chr(34)
mciSendString("open " & FileName & " alias myDevice", Nothing, 0, 0)
mciSendString("play myDevice", Nothing, 0, 0)
FileName = Chr(34) & (Button2.Text) & Chr(34)
mciSendString("open " & FileName & " alias myDevice", Nothing, 0, 0)
mciSendString("play myDevice", Nothing, 0, 0)
This code only plays the first song and will not play the second one...I'm thinking of creating another function similar to the one above with different name but still no luck.
Private Declare Function mciSendString2 Lib "winmm.dll" Alias "mciSendStringA" _
(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal _
uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
Any idea? Or is it possible to play multiple mp3 at the same time?
Although I am dealing with a different issue myself, I came across this in my search and can tell you the reason it cannot play the 2 files at the same time is because your alias is the same for both.
This method has worked well for me only during development but most computers I installed on would crash when i would issue the open command via mcisendstring. I haven't figured out why. Here's my code. Maybe it will help someone and maybe someone can figure out what I'm doing wrong. I've had problems getting 32 bit apps to run from my 64 bit development machine.
Imports System.Runtime.InteropServices
Imports System.Text
Public Class MediaPlayerClass
<DllImport("winmm.dll")> _
Private Shared Function mciSendString(ByVal command As String, ByVal buffer As StringBuilder, ByVal bufferSize As Integer, ByVal hwndCallback As IntPtr) As Integer
End Function
<DllImport("winmm.dll")> _
Private Shared Function mciGetErrorString(errCode As Integer, ByVal errMsg As StringBuilder, bufferSize As Integer) As Integer
End Function
<DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Public Shared Function GetShortPathName(ByVal longPath As String, _
<MarshalAs(UnmanagedType.LPTStr)> ByVal ShortPath As System.Text.StringBuilder, _
<MarshalAs(Runtime.InteropServices.UnmanagedType.U4)> ByVal bufferSize As Integer) As Integer
End Function
Private _filename As String
Private _MediaAlias As String
Private _Length As TimeSpan
Private _err As Integer
Public Property PlaylistId As Integer = 0
Private _OriginalVolume As Integer = 1000
Function ShortPathName(ByVal Path As String) As String
Dim sb As New System.Text.StringBuilder(1024)
Dim tempVal As Integer = GetShortPathName(Path, sb, 1024)
If tempVal <> 0 Then
Dim Result As String = sb.ToString()
Return Result
Else
Throw New Exception("Failed to return a short path")
End If
End Function
Public Sub New(Filename As String, MediaAlias As String)
_filename = ShortPathName(Filename)
_MediaAlias = MediaAlias.Replace(" ", "_")
'_Length = GetLength()
Try
My.Application.Log.WriteEntry("MediaPlayerClass.New - calling MCI OPEN")
' here is where it crashes
_err = mciSendString("open """ & _filename & """ alias " & MediaAlias, Nothing, 0, 0)
Catch ex As Exception
MsgBox(ex.ToString & vbCrLf & GetLastErrorMessage())
End Try
End Sub
Public Sub NewMP3(Filename As String)
Me.StopIt()
Me.CloseIt()
_filename = Filename
Try
My.Application.Log.WriteEntry("MediaPlayerClass.NewMP3 - calling MCI OPEN ")
_err = mciSendString("open """ & Filename & """ alias " & _MediaAlias, Nothing, 0, 0)
Catch ex As Exception
MsgBox(ex.ToString & vbCrLf & GetLastErrorMessage())
End Try
End Sub
Public ReadOnly Property Length As TimeSpan
Get
Return _length
End Get
End Property
Private Function GetLength() As TimeSpan
Dim lengthBuf As New StringBuilder(32)
Try
My.Application.Log.WriteEntry("MediaPlayerClass.GetLength - calling MCI OPEN")
_err = mciSendString("open """ & _filename & """ type waveaudio alias " & _MediaAlias, Nothing, 0, 0)
Catch ex As Exception
MsgBox(ex.ToString & vbCrLf & GetLastErrorMessage())
End Try
' Get the duration of the music
Try
_err = mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, 0)
Catch ex As Exception
MsgBox(ex.ToString & vbCrLf & GetLastErrorMessage())
End Try
'mciSendString("close wave", Nothing, 0, 0)
Dim len As Integer = Integer.TryParse(lengthBuf.ToString, len)
Dim ts As TimeSpan = TimeSpan.FromMilliseconds(len)
Return ts
End Function
Public Function PlayIt(Optional WaitUntilFinishedPlaying As Boolean = False) As Integer
Try
My.Application.Log.WriteEntry("MediaPlayerClass.PlayIt - calling MCI PLAY")
_err = mciSendString("play " & _MediaAlias, Nothing, 0, IntPtr.Zero)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
While WaitUntilFinishedPlaying
If IsPlaying() Then
Threading.Thread.Sleep(250)
Else
Exit While
End If
End While
Return _err
End Function
Public Function PauseIt() As Integer
_err = mciSendString("pause " & _MediaAlias, Nothing, 0, IntPtr.Zero)
Return _err
End Function
Public Function ResumeIt() As Integer
_err = mciSendString("resume " & _MediaAlias, Nothing, 0, IntPtr.Zero)
Return _err
End Function
Public Function StopIt() As Boolean
_err = mciSendString("stop " & _MediaAlias, Nothing, 0, IntPtr.Zero)
Return _err
End Function
Public Function CloseIt() As Boolean
_err = mciSendString("close " & _MediaAlias, Nothing, 0, IntPtr.Zero)
Return _err
End Function
Public Function IsPlaying() As Boolean
Dim returnData As New StringBuilder(128)
_err = mciSendString("status " & _MediaAlias & " mode", returnData, 128, IntPtr.Zero)
Return (returnData.Length = 7 AndAlso returnData.ToString.Substring(0, 7) = "playing")
End Function
Public Function SetVolume(vol As Integer) As Integer
_err = -1
If vol >= 0 And vol <= 1000 Then
_err = mciSendString("setaudio " & _MediaAlias & " volume to " & vol.ToString, Nothing, 0, IntPtr.Zero)
End If
Return _err
End Function
Public Sub FadeOutAndPause()
_OriginalVolume = GetVolume()
For x As Integer = 30 To 1 Step -1
Me.SetVolume(Int(x / 30 * _OriginalVolume))
Threading.Thread.Sleep(100)
Next
Me.PauseIt()
End Sub
Public Sub PlayAndFadeIn()
Me.PlayIt()
For x As Integer = 1 To 30 Step 1
Me.SetVolume(Int(x / 30 * _OriginalVolume))
Threading.Thread.Sleep(100)
Next
End Sub
Public Function GetVolume() As Integer
Dim returnData As New StringBuilder(128)
_err = mciSendString("status " & _MediaAlias & " volume", returnData, 128, IntPtr.Zero)
'MsgBox(returnData.ToString)
If _err = 0 Then
Return CInt(returnData.ToString)
Else
Return 1000
End If
End Function
Public Function SetBalance(bal As Integer) As Integer
If bal >= 0 AndAlso bal <= 1000 Then
_err = mciSendString("setaudio " & _MediaAlias & " left volume to " + (1000 - bal).ToString, Nothing, 0, IntPtr.Zero)
_err = mciSendString("setaudio " & _MediaAlias & " right volume to " + bal.ToString, Nothing, 0, IntPtr.Zero)
End If
Return _err
End Function
Public Function GetLastErrorMessage() As String
Dim returnData As New StringBuilder(128)
_err = mciGetErrorString(_err, returnData, 128)
Return returnData.ToString.Trim
End Function
Protected Overrides Sub Finalize()
MyBase.Finalize()
CloseIt()
End Sub
End Class