Closing multiple programs with the same name - vb.net

One part of my program is to close another program or the same program with the same name... I looked up how to do this and got this code:
Dim myprocesses() As Process
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each p As Process In myprocesses
If p.MainWindowTitle.Contains("notepad") Then
p.CloseMainWindow()
End If
Next
End Sub
It should work, however when I run it I'm getting an error message on the Next statement saying:
{"Object reference not set to an instance of an object."}
Does anyone know what's wrong with the above code?
UPDATE: Some of these answers seem to work :) Thanks. However there is a slight problem because sometimes the program doesn't load up until about 30 seconds (notepad was just put there for simplicity) so I need the code to close the PROCESS and not the actual program when it loads.
Hope you can understand that xD ^^^^

Obviously you declared the myprocesses() but null, so to achieve your task you must use GetProcessesByName
For Each process1 As Object In Process.GetProcessesByName("Notepad")
process1.Kill()
Next
But here's the proper way to manage the .exe process.

Try below code in your button click event:
Dim myProc As System.Diagnostics.Process
For Each myProc In System.Diagnostics.Process.GetProcesses
Console.WriteLine(myProc.MainWindowTitle)
If myProc.MainWindowTitle.ToUpper.Contains("NOTEPAD") Then
myProc.CloseMainWindow()
End If
Next

Related

Why does my subroutine, which handles a double-click event on a listbox, not work?

I have declared a Sub that is meant to trigger when the listbox 'lstStudents' is double-clicked. However, it does not trigger when this happened. There can't be an error in the code itself as it is auto-generated. Why does the code not function as expected? The code is below:
Private Sub lstStudents_DoubleClick(sender As Object, e As EventArgs) Handles lstStudents.DoubleClick
Msgbox("test")
End Sub
The message box is only present for testing purposes.
Could You try to delete that previous "lstStudents" and add new one then apply the "ListBox1_DoubleClick" on it again to make sure it works.
Otherwise let us know what is going there because I think your code is normally and it should be working 100%.

Access database connecting to VS but no data showing and runtime error

Trying to use an access database with Visual studio 15. After failure I found a number of tutorials and followed them with a new project and new database.
The database is connecting but the data inside the database won't display (although no error) and even using the built in save function in VB results in a run time error.
If anyone can point me in the right direction I'd be grateful. Code below.
Public Class Form1
Private Sub CustomersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles CustomersBindingNavigatorSaveItem.Click
Me.Validate()
Me.CustomersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.CustomersDataSet) 'Error is here****
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CustomersDataSet.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.CustomersDataSet.Customers)
End Sub
Private Sub BindingNavigatorDeleteItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorDeleteItem.Click
End Sub
Private Sub BindingNavigatorAddNewItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorAddNewItem.Click
End Sub
End Class
The error message I get is An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Unspecified error.
Here is a video that I made a while ago that should be able to help you, If you have any questions about it, i can definitely help you out.
https://www.youtube.com/watch?v=vvzY0LsAUNE
Also do you definitely need to use Access? I would recommend using an SQL database because when you publish your program, the end user may have to have a link to your access database in the same spot as yours, which can be a pain.
Nevertheless here is a video i also made regarding setting up an SQL database via Visual Studio.
https://www.youtube.com/watch?v=NLs44hxV514
If you have any issue, leave a comment and i will be happy to help you out :)
Keep In Mind
Don't forget that you need to also have a Number/unique word/or something a like in the Primary key column even if you haven't added any details to the database. eg Name and so on. If not your program may crash, so you could use the Try statement to fix this issue if the Primary Key column is left empty.

Optionally launch form in VB.Net console application

So I've set my application to a console type application and pointed it to a module containing just Sub Main, i.e.
Module mdlConsole
Sub Main(ByVal cmdArgs() As String)
If cmdArgs.Length = 0 Then
Dim frm As New frmMain
frm.Show()
End If
End Sub
End Module
Ideally if no arguments are supplied then the program would simply launch the primary form. The goal is to make this program (optionally) script-able from the command line. If arguments are supplied then the application form is not loaded and processes its features based off the command line arguments supplied.
As it is now, the program runs, briefly launches the form (frmMain) and then closes. What am I doing wrong or missing?
If you're not keen on giving me the answer, I'd be happy to be pointed in the right direction also. I don't expect anyone to just supply answers. I need to learn also.
Thanks!
For Winforms, you need to 'run' the App object, passing a form to use:
Sub Main(ByVal cmdArgs() As String)
If cmdArgs.Length = 0 Then
Dim frm As New frmMain
Application.Run(frm)
Else
' cmd line version
End If
End Sub
I see in your comment that you'd like to remove the console window that appears when running the form version of the program with the solution currently proposed. I cannot comment due to lack of reputation, so I will make this a full-fledged answer.
Consider approaching this from an inverse perspective: if you write the program as a forms application, opening it by default will bring up the form. But in the Form1_Load event, check the command line arguments; if they are greater than 0, simply run your (abbreviated) code logic here. At the end of the code, simply run Application.Exit(), like so:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Application.CommandLineArgs.Count > 0 Then
' Execute (abbreviated) code logic
' When finished, exit the program
Application.Exit()
End If
End Sub
This can also make your code cleaner and more practical if you're relying on a user-interface, because you can still access the values of form elements that the user would otherwise be modifying - but without the form showing on the screen (unless you prompt it to with a MsgBox or such).
This also works very nicely for Scheduled Tasks, as the user can run them manually with a user-interface, while the program executes without being visible via a scheduled task.
Kind of a follow-on to Chad's solution above I used the steps defined in How to have an invisible start up form? to avoid showing my form.
In short, create an Overrides subroutine that gets launched before Form1_Load:
This worked for me:
Protected Overrides Sub SetVisibleCore(ByVal value As Boolean)
If Not Me.IsHandleCreated Then
Me.CreateHandle()
value = False
MyBase.SetVisibleCore(value)
Else
Exit Sub
End If
If My.Application.CommandLineArgs.Count > 0 Then
MsgBox("Argument Sensed!")
' Execute (abbreviated) code logic
' When finished, exit the program
Me.Close()
Application.Exit()
Else
MyBase.SetVisibleCore(True)
End If
End Sub

Public Labels(Pointers)

I am working with VB 2010 for an application which requires me to go back to a sub. After some digging, I found out GoSub is no longer supported. I tried using Goto but apparently you can't use it outside the sub the label is in. I tried calling the sub put the parameters were not known to me.
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
I do not want to use the RunWorkerAsync because the worker will already be working. Please advise me on this matter.
It sounds like you are trying to solve a problem using procedural logic with an object-oriented tool.
If I understand you correctly, the sub is calling another section of code, and needs to return to the sub after it's finished. Make the called code itself a function or sub, and call it from the primary sub routine.

This BackgroundWorker is currently busy and cannot run multiple tasks concurrently

I am confused. Yes i understand I can't use the same backgroundworker to do two tasks at the same time. What I do not understand is this. Here is my code (all this thing does is set the marqueeanimationspeed of a progress bar...
'THE FOLLOWING SUB TOGGLES THE PROGRESS BAR
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'CHECK THE STATE OF THE PROGRESS BAR AND TOGGLE IT
If ToolStripProgressBar1.MarqueeAnimationSpeed = 0 Then
ToolStripProgressBar1.MarqueeAnimationSpeed = 22
End If
ToolStripProgressBar1.MarqueeAnimationSpeed = 0
End Sub
OK, so how long can this possibly take? Doesn't the worker do the task and exit? So I put in a pause (system.threading.thread.sleep(2000)... same problem, made it 20 seconds... same problem.
So I am assuming this is a simple thing I'm missing, but I've spent more than an hour searching and I don't get it.
All I am trying to accomplish here is to start the marquee progress bar while the UI is running something else, and then stop it. I assume I can create another backgroundworker and just use it, but I want to understand why the first one is not done with the task.
Thanks, and again, yes I spent an hour searching and I find all kinds of "solutions" but no explanation as to why this thing is not finished.
OK SO HERE IS THE SUB CALLING THE BGW
'THE FOLLOWING SUB FIRES THE SETTING CONNECTION STRINGS SUB
Private Sub SetCSButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetCSButton.Click
'START THE PROGRESS BAR & CHANGE THE LABEL
BackgroundWorker1.RunWorkerAsync()
Threading.Thread.Sleep(1000)
ToolStripStatusLabel1.Text = "Preparing the connection strings..."
Me.Refresh()
thread3 = New System.Threading.Thread(AddressOf SetConnectionStrings)
thread3.Start()
'STOP THE PROGRESS BAR & CHANGE THE LABEL
BackgroundWorker2.RunWorkerAsync()
Threading.Thread.Sleep(1000)
ToolStripStatusLabel1.Text = "Standing by..."
Me.Refresh()
End Sub**strong text**
I had a 20second delay but still the first BGW does not finish. I know this is something simple but I dont understand, that's all I am after here.
I DID change the code and do not use the same methodology as I was trying at the time I wrote this question... What I do not understand is why a simple operation is never, apparently, finishing... having said that, it DOES finish as I was able to show a msgbox using the runworkercompleted event. So, as I tried and failed to convey, thbis is not about the right or wrong way to code, I know it wa wrong and was just trying to be quick and dirty, regardless of that, I am not doing that now, but I do not understand why the BGW is "still working". There must be some simple thing I am ignorant about.
Thanks
The error is not in the posted code but where you start the Bgw.
But it is all irrelevant because you should not touch the GUI from DoWork:
Private Sub BackgroundWorker1_DoWork(...) Handles BackgroundWorker1.DoWork
'CHECK THE STATE OF THE PROGRESS BAR AND TOGGLE IT
If ToolStripProgressBar1.MarqueeAnimationSpeed = 0 Then ' Boom, cross-threading violation
ToolStripProgressBar1.MarqueeAnimationSpeed = 22
End If
I don't think you need a Bgw, thread or timer here. Just change the speed before/after the slow action.