I am working with the driving knowledge test program which consist of the multiple choice questions. I am having System.IO.IOException while trying to save the questions in the database file. Few hours earlier the same code was working fine but now it started to show the issue. The error is also mentioning that it cannot access the file and the file is being used by the another process. I also have added the picture to show the error that i faced
AddQuestions.vb
Imports System.IO
Public Class Questions
' Holds question number of question currently being updating or deleting.
Dim currentlyEditingDeleteingQueNo As Integer
Private Sub QuestionForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
TXTQuestionNo.Enabled = False
TXTQuestionNo.Text = gloTestQuestions.Count + 1
Fill_Grid()
End Sub
' Insert a new question in array list.
Private Sub BTNAdd_Click(sender As System.Object, e As System.EventArgs) Handles BTNAdd.Click
Dim question As Trivia_Data
question.intQuestionNo = TXTQuestionNo.Text
question.StrQuestion = TXTQuestion.Text
question.StrAnswer1 = TXTAnswer1.Text
question.StrAnswer2 = TXTAnswer2.Text
question.StrAnswer3 = TXTAnswer3.Text
question.StrAnswer4 = TXTAnswer4.Text
question.intCorrectAnswer = Integer.Parse(TXTAnswer5.Text)
gloTestQuestions.Add(question)
Fill_Grid()
MessageBox.Show("Question inserted successfully....")
ClearText()
End Sub
' Clears all text boxes for next question and displays possible question for it.
Private Sub ClearText()
TXTAnswer1.Clear()
TXTAnswer2.Clear()
TXTAnswer3.Clear()
TXTAnswer4.Clear()
TXTAnswer5.Clear()
TXTQuestion.Clear()
TXTQuestionNo.Clear()
TXTQuestionNo.Text = gloTestQuestions.Count + 1
End Sub
' Fills data grid view controls with available questions in a system.
Private Sub Fill_Grid()
Dim dt As DataTable
dt = New DataTable()
dt.Columns.Add("Question Number")
dt.Columns.Add("Question")
dt.Columns.Add("Answer1")
dt.Columns.Add("Answer2")
dt.Columns.Add("Answer3")
dt.Columns.Add("Answer4")
dt.Columns.Add("CorrectAnswer")
Dim question As Trivia_Data
For j = 0 To gloTestQuestions.Count - 1
dt.Rows.Add()
question = CType(gloTestQuestions(j), Trivia_Data)
dt.Rows(j)("Question Number") = question.intQuestionNo.ToString()
dt.Rows(j)("Question") = question.StrQuestion
dt.Rows(j)("Answer1") = question.StrAnswer1
dt.Rows(j)("Answer2") = question.StrAnswer2
dt.Rows(j)("Answer3") = question.StrAnswer3
dt.Rows(j)("Answer4") = question.StrAnswer4
dt.Rows(j)("CorrectAnswer") = question.intCorrectAnswer
Next
'DataGridView1.DataSource = dt
End Sub
' Searchs a question by user supplied question number using binary search technique.
Private Sub BTNFind_Click(sender As System.Object, e As System.EventArgs) Handles BTNFind.Click
Dim totalAddedQuestion As Integer = gloTestQuestions.Count
Dim questionNo = InputBox("Enter the question number that you want to search:")
If questionNo > gloTestQuestions.Count Or questionNo = 0 Then
MessageBox.Show("Question doesn't exist..........")
ClearText()
Exit Sub
Else
Dim compare As New ArrayListIntegerComparere
gloTestQuestions.Sort(compare)
Fill_Grid()
Dim max As Integer
Dim min As Integer
Dim mid As Integer
min = 0
max = totalAddedQuestion - 1
While (max >= min)
mid = (min + max) / 2
Dim question As Trivia_Data = CType(gloTestQuestions(mid), Trivia_Data)
If question.intQuestionNo < questionNo Then
min = mid + 1
ElseIf question.intQuestionNo > questionNo Then
max = mid - 1
Else
TXTAnswer1.Text = question.StrAnswer1
TXTAnswer2.Text = question.StrAnswer2
TXTAnswer3.Text = question.StrAnswer3
TXTAnswer4.Text = question.StrAnswer4
TXTAnswer5.Text = question.intCorrectAnswer
TXTQuestion.Text = question.StrQuestion
TXTQuestionNo.Text = question.intQuestionNo
currentlyEditingDeleteingQueNo = mid
MessageBox.Show("Question found............")
BTNUpdate.Enabled = True
BTNDelete.Enabled = True
Exit Sub
End If
End While
End If
MessageBox.Show("Question doesn't exist.................")
ClearText()
End Sub
' Saves questions in binary file and closes the file after writing operations.
Private Sub BTNSave_Click(sender As System.Object, e As System.EventArgs) Handles BTNSave.Click
Dim file As New FileStream(Directory.GetCurrentDirectory() & "\Question.dat", FileMode.Create, FileAccess.Write)
Dim fileWrite As BinaryWriter = New BinaryWriter(file)
Dim question As Trivia_Data
For i = 0 To gloTestQuestions.Count - 1
question = CType(gloTestQuestions(i), Trivia_Data)
fileWrite.Write(Convert.ToInt16(question.intQuestionNo))
fileWrite.Write(question.StrQuestion)
fileWrite.Write(question.StrAnswer1)
fileWrite.Write(question.StrAnswer2)
fileWrite.Write(question.StrAnswer3)
fileWrite.Write(question.StrAnswer4)
fileWrite.Write(Convert.ToInt16(question.intCorrectAnswer))
Next
fileWrite.Close()
file.Close()
MessageBox.Show("Questions saved in file successfully..........")
End Sub
' Updates exisitng question as per newly provided values.
Private Sub BTNUpdate_Click(sender As System.Object, e As System.EventArgs) Handles BTNUpdate.Click
Dim question As Trivia_Data = CType(gloTestQuestions(currentlyEditingDeleteingQueNo), Trivia_Data)
question.StrAnswer1 = TXTAnswer1.Text
question.StrAnswer2 = TXTAnswer2.Text
question.StrAnswer3 = TXTAnswer3.Text
question.StrAnswer4 = TXTAnswer4.Text
question.intCorrectAnswer = Integer.Parse(TXTAnswer5.Text)
question.StrQuestion = TXTQuestion.Text
gloTestQuestions(currentlyEditingDeleteingQueNo) = question
MessageBox.Show("Question updated successfully...................")
BTNUpdate.Enabled = False
BTNDelete.Enabled = False
ClearText()
Fill_Grid()
End Sub
' Deletes a current question from the arraylist.
Private Sub BTNDelete_Click(sender As System.Object, e As System.EventArgs) Handles BTNDelete.Click
gloTestQuestions.RemoveAt(currentlyEditingDeleteingQueNo)
Fill_Grid()
ClearText()
MessageBox.Show("Question removed successfully.....")
BTNDelete.Enabled = False
BTNUpdate.Enabled = False
End Sub
' Closes the Question form
Private Sub BTNClose_Click(sender As System.Object, e As System.EventArgs) Handles BTNClose.Click
Me.Close()
End Sub
End Class
Did you encounter any exceptions during testing which may have caused the file not being correctly closed (file.close()) by your own application?
Do you have the file (Question.dat) open in another program?
Does an instance of your application still run and keeps the file open?
When dealing with this sort of operations it is better to rewrite your code something like this :
EDIT VB .NET (pseudo code)
Try
Using file As New File
' your code...
End Using
Catch exception As Exception
' log and/or show to user...
Finally
' your code...
file.Close()
End Try
Original C# code
try{
// If the file class implements IDisposable
using(File file = new file()){
// your code...
...
}
}
catch(Exception ex){
// log and/or show to user
}
finally{
file.close();
}
It is hard to say what process/application has the file in use or locked so for now I should say, close and reopen Visual Studio or even worse restart Windows.
Related
I'm very new to coding so my code is very basic but I am trying to rewrite a file using an item selected from a list box. The code is a recreation of my full code so it's not as thorough but I want to be able to change the "availability" of a product for a website (In theory because this is not a professional project). When I try to read or write the file an error message comes up saying "The process cannot access the file because it is being used by another process".
Dim FileRewrite As String = "FileRewrite.txt"
Dim ValidateID As Boolean
Dim Read As String
Dim IDR As String
Dim YNR As String
Private Sub TxtBxID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtBxID.TextChanged
If TxtBxID.Text.Length = 2 Then
ValidateID = True
Else
ValidateID = False
End If
End Sub
Private Sub BtnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAdd.Click
Dim ID As String
Dim YN As String
Dim Writer As New System.IO.StreamWriter(FileRewrite, True)
If ValidateID = True Then
ID = TxtBxID.Text
If CBxYN.Checked = True Then
YN = "YES"
Else
YN = "NO "
End If
Writer.WriteLine(LSet(ID, 3) & LSet(YN, 3))
Writer.Close()
LstBxItems.Items.Clear()
Dim Reader As New System.IO.StreamReader(FileRewrite, True)
Do While Reader.Peek >= 0
LstBxItems.Items.Add(Reader.ReadLine)
Loop
Reader.Close()
Else
MsgBox("Please enter a 2 digit ID")
End If
End Sub
Private Sub BtnChange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnChange.Click
Dim ItemToChange As String
Dim Reader As New System.IO.StreamReader(FileRewrite, True)
ItemToChange = LstBxItems.SelectedItem
IDR = Mid(ItemToChange, 1, 3)
YNR = Mid(ItemToChange, 4, 6)
Do While Reader.Peek >= 0
Read = Reader.ReadLine
Writer()
Loop
Reader.Close()
End Sub
Private Sub Writer()
Dim Writer As New System.IO.StreamWriter(FileRewrite, True)
If Mid(Read, 1, 3) = IDR Then
If YNR = "YES" Then
YNR = "NO "
Else
YNR = "YES"
End If
Writer.WriteLine(LSet(IDR, 3) & LSet(YNR, 3))
Writer.Close()
End If
End Sub
I expect the availability of the product in the file to change from yes to no or no to yes but the reader and writer will not work
You cannot write to the file while looping through the same file to read via Reader.Peek
So I did something similar a while ago, but this is essentially a username checker for a (specific) website, they can load in usernames via text file and it will put it into a list box, now I have the start button and it's meant to check each username. Before, however, it froze the program when they checked, but it worked. I tried making it "threaded" so it didn't freeze.
The problem now is that it doesn't check them all, and finishes instantly.
CODE:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Button6.Enabled = False
Dim goodUsers As New SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
Dim flag As Boolean
Dim Incomplete As Integer = 0
Dim Taken As Integer = 0
Dim sb As New StringBuilder
If goodUsers.ShowDialog() = DialogResult.OK Then
Dim checkerMT As New Thread(
Sub()
For Each i As String In UsernameList.Items
WebRequest.Create("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString)
Dim cResult As String = New System.Net.WebClient().DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If cResult = "taken" Then
flag = False
ElseIf cResult = "nottaken" Then
flag = True
End If
If flag = True Then
sb.Append(i & vbNewLine)
Else
Incomplete = Incomplete + 1
Taken = UsernameList.Items.Count - Incomplete
End If
Next
End Sub
)
checkerMT.Start()
Try
File.WriteAllText(goodUsers.FileName, sb.ToString)
Catch ex As Exception
Exit Sub
End Try
End If
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
Button6.Enabled = True
End Sub
You cannot access UI elements (UsernameList.Items) from a thread other than the UI. Instead add a background worker to your form to handle the basic threading stuff (progress reporting, finish reporting, exception handling). Pass into this an object that contains the settings your job needs to do its work without interacting with the ui.
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Button6.Enabled = False
Dim goodUsers As New SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
If goodUsers.ShowDialog() = DialogResult.OK Then
'Note: You'll need to add the filenames
BackgroundWorker1.RunWorkerAsync(New State() With {.Names = {}, .FileName = goodUsers.FileName})
End If
End Sub
Class State
Public Names As List(Of String)
Public StringBuilder As New System.Text.StringBuilder
Public Incomplete As Integer
Public Taken As Integer
Public FileName As String
End Class
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim state = CType(e.Argument, State)
For Each i As String In state.Names
Using cli = New System.Net.WebClient()
Dim cResult = cli.DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If cResult = "nottaken" Then
state.StringBuilder.Append(i & vbNewLine)
Else
state.Incomplete = state.Incomplete + 1
state.Taken = state.Names.Count - state.Incomplete
End If
End Using
Next
IO.File.WriteAllText(state.FileName, state.StringBuilder.ToString)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error IsNot Nothing Then
MessageBox.Show(e.Error.ToString(), "Error")
Else
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
End If
Button6.Enabled = True
End Sub
The SaveFileDialog can be used as "Using directive"
Why do you create a webrequest on the one hand, and on the other hand use a webclient? That does not make sense at all.
Instead of your strange if condition, write:
flag = (cResult.Equals("nottaken"))
All code you want to run after the actions you are currently running in your thread have to be in your thread as well, because it is async.
You have to invoke if you use user controls within a thread
and so on..
Please turn Option Strict On and Option Infer Off
There are lots of other things you could do better.
Please remove the webrequest and webclient combination yourself, that does not make sense at all.
Take a look at this, I cleared it a little bit:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim Incomplete As Integer = 0
Dim Taken As Integer = 0
Dim sb As New StringBuilder
Using goodUsers As SaveFileDialog = new SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
If not goodUsers.ShowDialog() = DialogResult.OK Then Exit Sub
Dim checkerMT As New Thread(
Sub()
Me.invoke(sub()
Button6.Enabled = False
For Each i As String In UsernameList.Items
WebRequest.Create("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString)
Dim cResult As String = New System.Net.WebClient().DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If (cResult.toLower().Equals("nottaken")) Then
sb.Append(String.Concat(i , Environment.NewLine)
Else
Incomplete += 1
Taken = UsernameList.Items.Count - Incomplete
End If
Next
File.WriteAllText(goodUsers.FileName, sb.ToString)
Button6.Enabled = True
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
End Sub)
End Sub
)
checkerMT.IsBackground = True;
checkerMT.Start()
End Sub
I've recently been exposed to vb.net scripting and I am having some trouble figuring out how to accomplish a task. I'm supposed to create a program that will automate an end user process but right now it only works for one specific id(because I've hardcoded a value to make the script run). I've scripted the use of StreamReader to loop through all the possible entries, but I can't figure out how to put that result into a variable so the program will automatically read the id selected and proceed through the steps, then loop until all id's identified via StreamReader have been processed. I apologize if this has been asked before, I am not very familiar with the terminology.
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Application.DoEvents()
End
End Sub
Private Sub Form1_FormLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
uxNote.Text = "Starting"
Me.Update()
RunApp()
Me.Close()
End Sub
Sub RunApp()
Dim b As New BostonWorkStation
Dim myHandle As Long
b.Shell_("C:\Software\Application.exe")
b.Activate("AppCaption", True)
b.Connect("AppCaption", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Update()
b.Wait(2)
b.Pause("#378,423")
b.Tab_("user")
b.Enter("password")
b.Wait(2)
b.Shell_("C:\Software\Application2.exe")
b.Activate("App2Caption", True)
b.Wait(4)
b.Connect("App2Caption", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Update()
b.Wait(4)
b.Smart.Create("App2Caption#726,1088", -1024, -633, 0)
b.Smart.Click(False, False)
b.Wait(3)
b.Activate("Patient Lookup", True)
b.Connect("Patient Lookup", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Update()
b.Wait(1)
b.Pause("#104,423")
ProcessPatients(b)
b.Enter("10001") 'hardcoded id this is where I would like a variable to pull in the value
b.Wait(2)
'some more code steps here specific to what should be done once patient id has been selected
End Sub
Sub ProcessPatients(ByVal w As BostonWorkStation)
Dim record() As String
Dim sr As New StreamReader("my path for csv or txt file")
Do While sr.Peek > -1
record = sr.ReadLine.Split(CChar("|"))
Loop
sr.Close()
End Sub
I imagine it would look something like this:
Imports System.IO
Public Class Form1
Private Sub Form1_FormLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
uxNote.Text = "Starting"
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
RunApp()
End Sub
Sub RunApp()
Dim b As New BostonWorkStation
Dim myHandle As Long
b.Shell_("C:\Software\Application.exe")
b.Activate("AppCaption", True)
b.Connect("AppCaption", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Refresh()
Application.DoEvents()
b.Wait(2)
b.Pause("#378,423")
b.Tab_("user")
b.Enter("password")
b.Wait(2)
b.Shell_("C:\Software\Application2.exe")
b.Activate("App2Caption", True)
b.Wait(4)
b.Connect("App2Caption", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Refresh()
Application.DoEvents()
b.Wait(4)
b.Smart.Create("App2Caption#726,1088", -1024, -633, 0)
b.Smart.Click(False, False)
b.Wait(3)
b.Activate("Patient Lookup", True)
b.Connect("Patient Lookup", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Refresh()
Application.DoEvents()
b.Wait(1)
b.Pause("#104,423")
ProcessPatients(b)
Me.Close()
End Sub
Sub ProcessPatients(ByVal w As BostonWorkStation)
Dim ID As String
Dim record() As String
Dim sr As New StreamReader("my path for csv or txt file")
Do While Not sr.EndOfStream
record = sr.ReadLine.Split(CChar("|"))
ID = record(0) ' <-- grab your "ID" from somewhere in "record"
w.Enter(ID)
w.Wait(2)
'some more code steps here specific to what should be done once patient id has been selected
Loop
sr.Close()
End Sub
End Class
I have an application to export ListView to Excel sheet , and im trying to do this in background but i have error in SaveFileDialog.showdialog().This is the error :
An exception of type 'System.Threading.ThreadStateException' occurred
in System.Windows.Forms.dll but was not handled in user code
Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.
and this is my code :
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Public Sub saveExcelFile(ByVal FileName As String)
Try
Dim xls As New Excel.Application
Dim sheet As Excel.Worksheet
Dim i As Integer
xls.Workbooks.Add()
sheet = xls.ActiveWorkbook.ActiveSheet
Dim row As Integer = 1
Dim col As Integer = 1
For i = 0 To Me.ListView1.Columns.Count - 1
sheet.Cells(1, i + 1) = Me.ListView1.Columns(i).Text
Next
For i = 0 To Me.ListView1.Items.Count - 1
For j = 0 To Me.ListView1.Items(i).SubItems.Count - 1
sheet.Cells(i + 2, j + 1) = Me.ListView1.Items(i).SubItems(j).Text
Next
Next
row += 1
col = 1
' for the header
sheet.Rows(1).Font.Name = "Cooper Black"
sheet.Rows(1).Font.size = 12
sheet.Rows(1).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
Dim mycol As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#148cf7")
sheet.Rows(1).Font.color = mycol
' for all the sheet without header
sheet.Range("a2", "z1000").Font.Name = "Arial"
sheet.Range("a2", "z1000").Font.Size = 13
sheet.Range("a2", "z1000").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
sheet.Range("A1:X1").EntireColumn.AutoFit()
sheet.Range("A1:X1").EntireRow.AutoFit()
xls.ActiveWorkbook.SaveAs(FileName)
xls.Workbooks.Close()
xls.Quit()
Catch ex As Exception
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
Dim saveFileDialog1 As New SaveFileDialog
saveFileDialog1.Filter = "Excel File|*.xlsx"
saveFileDialog1.Title = "Save an Excel File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
saveExcelFile(saveFileDialog1.FileName)
End If
Catch ex As Exception
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("done")
End Sub
You could move everything concerning SaveFileDialog1 to Button3_Click and store the filename in a Private variable, so it can be used later in BackgroundWorker1_DoWork.
Private _filename As String
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel Files (*.xlsx)|*.xslx"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
_filename = SaveFileDialog1.FileName
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
...
book.SaveAs(_filename)
...
End Sub
i put this code in load form and everything is perfect:
Control.CheckForIllegalCrossThreadCalls = False
Ok, so I'm making a program that will read from a text file, convert each line into an array, the. Send each of those lines 1 per tick. This is in 2010 Visual Basic.
Closest I've gotten is sending all at once, I worked on it over night and am slowly destroying it.
Ideally, I want Button 1 click to populate the array from the file at LocationTB then start the timer. The timer should send a line at a time on the GapTB interval.
Public Class Form1
Public TextLine As String
Public MyFileName As String
Public MyNewLine(1000) As String
Private Property z As Integer
Private Property objReader As Object
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If RadioButton2.Checked = True Then
Dim Textline As String = ""
Dim FILE_NAME As String = LocationTB.Text
Dim objReader As New System.IO.StreamReader(FILE_NAME)
MyFileName = LocationTB.Text
FileOpen(1, MyFileName, OpenMode.Input, OpenAccess.Read, OpenShare.Shared)
z = 0
Do Until EOF(1)
MyNewLine(z) = LineInput(1)
z = z + 1
Loop
FileClose(1)
End If
Timer1.Interval = GapTB.Text
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If RadioButton1.Checked = True Then
AppActivate(Hook.Text)
SendKeys.Send(SimpleTB.Text)
SendKeys.Send((Chr(13)))
ElseIf RadioButton2.Checked = True Then
For Each
TextLine = TextLine & objReader.ReadLine
AppActivate(Hook.Text)
SendKeys.Send(TextLine)
SendKeys.Send((Chr(13)))
Next
Else
MsgBox("File Does Not Exist")
End If
End Sub
Is this the kind of thing you're looking for?
It'll write the contents of a file (in this instance "C:\mark.txt") to the output window in Visual Studio.
Public Class Form1
Private myTimer As Timer
Private lines As String()
Private currentLine As Integer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
lines = IO.File.ReadAllLines("C:\mark.txt")
currentLine = 0
myTimer = New Timer()
AddHandler myTimer.Tick, AddressOf myTimer_Tick
myTimer.Interval = 1000
myTimer.Enabled = True
End Sub
Private Sub myTimer_Tick(sender As Object, e As EventArgs)
If currentLine < lines.Count Then
Dim lineToSend As String = lines(currentLine)
Debug.Print(lineToSend)
currentLine += 1
Else
myTimer.Enabled = False
End If
End Sub
End Class
Caveat
The above code isn't scalable. If you're SURE the file will always be small then it will do (that said, they're never always small).
To make this scalable you'd need to hold the file open, and read each line as you need it, not load the entire file contents at once.
I know how to do it to a application I started myself: Here's the code to make Calculator work:
Dim ProcID As Integer
' Start the Calculator application, and store the process id.
ProcID = Shell("CALC.EXE", AppWinStyle.NormalFocus)
' Activate the Calculator application.
AppActivate(ProcID)
' Send the keystrokes to the Calculator application.
My.Computer.Keyboard.SendKeys("22", True)
My.Computer.Keyboard.SendKeys("*", True)
My.Computer.Keyboard.SendKeys("44", True)
My.Computer.Keyboard.SendKeys("=", True)
' The result is 22 * 44 = 968.
AppActivate should know the exact title of the form to activate. If not known, iterate the Processes to locate yours. If the title is correctly specified it should work