Run program without form on windows startup - vb.net

What basically i want is to show is:
notifyicon.visible = true
I mean to show a tray icon when the windows starts up but the program form should not be shown ,how could i achieve it ?
I got to know that by adding to registry you can run the program on startup example below
Dim regkey As RegistryKey
regkey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", True)
If (runonstartupToolStripMenuItem.Checked = True) Then
' Add the value in the registry so that the application runs at startup
regkey.SetValue("Your Application Name", Application.ExecutablePath.ToString())
Else
' Remove the value from the registry so that the application doesn't start
regkey.DeleteValue("Your Application Name", False)
End If
but this will run the whole program and will make form show up which i do not want unless user manually starts it.

Add this code to your form:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Hide() ' <= Required
Me.ShowInTaskbar = False ' <= Required
NotifyIcon1.Visible = True
NotifyIcon1.ShowBalloonTip(10000)
End Sub
When the program opens when the windows starts it should open with a unique parameter,
And when the unique parameter is found the form will be hidden,
Conversely if the user opens the program, will not have the parameter and then the form can show.

I am use checkbox to set and unset:
Private Sub cbStartup_CheckedChanged(sender As Object, e As EventArgs) Handles cbStartup.CheckedChanged
Dim applicationName As String = Application.ProductName
Dim applicationPath As String = Application.ExecutablePath
If cbStartup.Checked = True Then
Dim regKey As Microsoft.Win32.RegistryKey
regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
regKey.SetValue(applicationName, """" & applicationPath & """")
regKey.Close()
Else
Dim regKey As Microsoft.Win32.RegistryKey
regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
regKey.DeleteValue(applicationName, False)
regKey.Close()
End If
End Sub
Test working on VS 2015 run on Windows 10 64Bit.

Related

VB.NET Form.Show closes the application for unknown reason

VB.NET Framework 4.7.2
Visual Studio Community 2019 V16.11.2
I have a WinForms application and, for the most part, I start with a form to display the loading of datatables. This is handled in the Application Events module:
Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
If String.IsNullOrEmpty(My.Settings.TheCompany) Then
MainForm = FormConnection
Else
MainForm = FormDataLoad
End If
End Sub
When the datatables are all loaded the FormDataLoad has a close button which is enabled by the procedure which loads all the datatables:
With FormDataLoad
.ButtonClose.Visible = True
End With
When the button is pressed it calls another form which displays various charts etc based on the datatables which have been loaded:
Private Sub ButtonClose_Click(sender As Object, e As EventArgs) Handles ButtonClose.Click
Me.Close()
End Sub
Private Sub FormDataLoad_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
With FormOverview
.Show()
End With
End Sub
When FormOverview loads, its labels, charts etc are all initialised and drawn BUT, mysteriously, the form closes and the application ends. The Application Shutdown event is raised:
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
Private Sub MyApplication_Shutdown(sender As Object, e As EventArgs) Handles Me.Shutdown
MessageBox.Show("Closing the application for some unknown reason")
End Sub
When this message box is displayed it means that the application has closed but not as a result of any unhandled exception. Nowhere in the project is there any code to call FormOverview.close so I am at a loss to understand what is happening.
The form load code is here:
Private Sub FormOverview_Load(sender As Object, e As EventArgs) Handles Me.Load
With Me
'Set the form caption and back colour and font
.Text = "Retail Management Hero Data Visualisation Overview"
.BackColor = Color.GhostWhite
.Font = U.BasicFontSmall
'Add event handler for the DAL
AddHandler D.ConnectionOpened, AddressOf Connected
'Form level variables for the KPJs
Dim ITO As String = ""
Dim ATV As String = ""
Dim CRR As String = ""
Dim GMROI As String = ""
Dim OOS As String = ""
Dim StocksSales As String = ""
With KPIData.Rows(0)
Me.Text = My.Settings.TheCompany & " " & Me.Text
ITO = .Item("ITO").ToString
CRR = .Item("CRR").ToString
ATV = "€" & .Item("ATV").ToString
GMROI = "€" & .Item("GMROI").ToString
OOS = .Item("OOSRatio").ToString
StocksSales = .Item("StocksToSales").ToString
End With
For Each CTL As Control In .Controls
If TypeOf CTL Is Label Then
With CTL
If .Name.Contains("Value") Then
.Font = U.BasicFontSuperLarge
.BackColor = Color.Yellow
Else
.BackColor = U.Spurs
.ForeColor = Color.GhostWhite
End If
End With
End If
Next
With .LabelReportDate
.Text = "Reports As Of " & ReportDate
End With
With .LabelATVValue
.Text = U.DecimalToSuperSubFormat(ATV, True)
End With
With .LabelGMROIValue
.Text = U.DecimalToSuperSubFormat(GMROI, True)
End With
With .LabelCRRValue
.Text = U.DecimalToSuperSubFormat(CRR, True) & "%"
End With
With .LabelITOValue
.Text = U.DecimalToSuperSubFormat(ITO, True)
End With
With .LabelOOSValue
.Text = U.DecimalToSuperSubFormat(OOS, True) & "%"
End With
With .LabelStocksSalesValue
.Text = U.DecimalToSuperSubFormat(StocksSales, True) & "%"
End With
'Extract the names of the X and Y axes
Dim Xname As String = ""
Dim Yname As String = ""
With WineData
Xname = .Columns("Department").ColumnName
Yname = .Columns("Day").ColumnName
End With
'Draw the charts
DrawColumnChart(WineData, .ChartWine, "Wine sales", Xname, Yname, 250, False)
DrawColumnChart(OtherData, .ChartNonWine, "Other sales", Xname, Yname, 25, False)
'Centre on the screen
.CenterToScreen()
End With
End Sub
So, what should happen is that this form displays centre screen with charts etc all displayed correctly.
If anyone has any ideas I would be most grateful.
Dermot
I found out what was causing the problem.
In the Project's properties, in the Application tab, there Combo selector, Shutdown mode.
The option I had selected was When startup form closes - by changing this to When last form closes the issue went away.
Like many problems, when you look at it too long you can't see the woods for the trees.

How to run an external script using visual basic?

I want to make a Windows application using visual basic and visual studio 2017.
Here I want to run an external Python script which will run when 'Button 1' is pressed in the windows form. It will take input from the Textbox in the form and do some calculations and then return the result and put it back in the Textbox in the form.
The python code can be either this :
r = input()
p = 2*3.14*r
print(p) #Instead of print(p) something that can return the value to the form
OR This:
def peri(r):
p = 2*3.14*r
return p
I managed to find this solution for you and i really hope it works:
1.Write your python code , for example : print("Hello world python !!") in text file and save to .py
2.Create project at VB.NET, drag component 1 button and 1 textbox into form.
3.Double click button1, at event click button1 write this code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim proc As Process = New Process
proc.StartInfo.FileName = "C:\Python34\python.exe" 'Default Python Installation
proc.StartInfo.Arguments = pathmypythonfile.py
proc.StartInfo.UseShellExecute = False 'required for redirect.
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden 'don't show commandprompt.
proc.StartInfo.CreateNoWindow = True
proc.StartInfo.RedirectStandardOutput = True 'captures output from commandprompt.
proc.Start()
AddHandler proc.OutputDataReceived, AddressOf proccess_OutputDataReceived
proc.BeginOutputReadLine()
proc.WaitForExit()
TextBox1.Text = Value
End Sub
Public sub proccess_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
On Error Resume Next
If e.Data = "" Then
Else
Value = e.Data
End If
End sub
4. Create module file, and write this variable global :
Module module
Public Value As String
End Module
5. Running the application, if textbox1 have populated with some string then your code was success.
HERE is a lick with the full process.
This is the answer by #Dimitar_Georgiev, with small corrections and formatting fixes.
I managed to find this solution for you and i really hope it works:
Write your python code , for example : print("Hello world python !!") in text file and save to .py
Create project at VB.NET, drag component 1 button and 1 textbox into form.
Double click button1, at event click button1 write this code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim proc As Process = New Process
proc.StartInfo.FileName = "C:\Python34\python.exe" 'Default Python Installation
proc.StartInfo.Arguments = "C:\path\to\my\pythonfile.py"
proc.StartInfo.UseShellExecute = False 'required for redirect.
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden 'don't show commandprompt.
proc.StartInfo.CreateNoWindow = True
proc.StartInfo.RedirectStandardOutput = True 'captures output from commandprompt.
proc.Start()
AddHandler proc.OutputDataReceived, AddressOf proccess_OutputDataReceived
proc.BeginOutputReadLine()
proc.WaitForExit()
TextBox1.Text = Value
End Sub
Public sub proccess_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
On Error Resume Next
If e.Data = "" Then
Else
Value = e.Data
End If
End sub
Create module file, and write this variable global :
Module module
Public Value As String
End Module
Running the application, if textbox1 have populated with some string then your code was success.
HERE is a lick with the full process.

Notify Icon appears to be disposed after running batch file

I have a WinForms application in VB.net with a NotifyIcon with ContextMenu attached. For some reason when I click the menu item to set the main form as Me.TopMost = false, then copy the batch file to the PC and run it, the NotifyIcon seems to get disposed (no longer appears in system tray). This only appears to happen intermittently.... I have no idea what could be causing this.
The reason that I am thinking that the NotifyIcon is disposed is because if I add a readerNotify.Visible = True after the operation the icon still does not re-appear. See below for the code
Private Sub ResetWindowsUpdateComponentsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ResetWindowsUpdateComponentsToolStripMenuItem.Click
'Adds Windows Update Components reset batch file to ProgramData and runs the file
Dim fileContent As String = My.Resources.WindowsUpdate_Components_Reset
Dim filename As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\WUCR.bat"
Me.TopMost = False
clearWUCache()
My.Computer.FileSystem.WriteAllText(filename, fileContent, False, System.Text.Encoding.ASCII)
'**WHERE NOTIFYICON SEEMS TO DIE**
Dim objProcess As Process = New Process
objProcess.StartInfo.FileName = filename
objProcess.Start()
objProcess.WaitForExit()
prgBarTemps.Value = 100
lblStatus.Text = "Windows Update components reset successfully!"
Me.TopMost = True
End Sub
Private Sub clearWUCache()
Dim wuCacheFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Windows) & "\SoftwareDistribution\Download"
Try
WebFixProcesses.deleteFolders(wuCacheFolder)
WebFixProcesses.deleteFiles(wuCacheFolder)
Catch ex As Exception
MsgBox(ex.Message)
Dim wuCacheDirect As String = "C:\Windows\SoftwareDistribution\Download"
WebFixProcesses.deleteFolders(wuCacheDirect)
WebFixProcesses.deleteFiles(wuCacheDirect)
lblStatus.Text = "Press a button to fix problems"
End Try
End Sub
I must be doing something wrong here in the way I am setting up the batch file in conjunction with setting Me.TopMost = False or something like that. Any help on this is greatly appreciated!
EDIT:
Here is some additional info from my Form.Designer InitializeComponent() method on the NotifyIcon.
Private Sub InitializeComponent()
'Have omitted other controls
Me.readerNotify = New System.Windows.Forms.NotifyIcon(Me.components)
'readerNotify
'
Me.readerNotify.ContextMenuStrip = Me.ContextMenu
Me.readerNotify.Icon = CType(resources.GetObject("readerNotify.Icon"), System.Drawing.Icon)
Me.readerNotify.Text = "WebFix"
Me.readerNotify.Visible = True
End Sub
Public WithEvents readerNotify As System.Windows.Forms.NotifyIcon

How to hide Windows 7 Open File Security when running certain EXE file using VB.NET?

Hello dearest community,
I am trying to build a simple AutoUpdate application using VB.NET. It was quite simple. That is, I put the newest ZIP file in my hosting site, and then download it using WebClient.DownloadFileAsync. After it get downloaded, I extract it using http://stahlforce.com/dev/unzip.exe
But each time I run the unzip.exe using Process.start, Windows 7 always show Open File Security.
Is it possible for VB.NET to bypass such security restriction?
Thanks.
Btw, this is my code of using WebClient.DownloadFileAsync, in case any one google about it and landed on this page :
Public Class AutoUpdate
Dim installationFolder As String = "C:\Program Files\xyz\abc\"
Dim updateFileNameTarget As String
Private Sub btnStartUpdte_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartUpdte.Click
lblPercent.Text = ""
lblDownloading.Text = ""
lblDownloading.Text = ""
pbDownloadStatus.Value = 0
Dim wc As New WebClient
AddHandler wc.DownloadFileCompleted, AddressOf downloadComplete
AddHandler wc.DownloadProgressChanged, AddressOf progressChanged
Dim path As String = "http://xyz.abc.com/test.zip"
updateFileNameTarget = installationFolder & "test.zip"
Try
If File.Exists(updateFileNameTarget) Then
File.Delete(updateFileNameTarget)
End If
lblDownloading.Text = "Downloading " & path
wc.DownloadFileAsync(New Uri(path), updateFileNameTarget)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub progressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
pbDownloadStatus.Value = e.ProgressPercentage
lblPercent.Text = e.ProgressPercentage & "%"
End Sub
Private Sub downloadComplete(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
MessageBox.Show("Download complete. Now extracting")
Dim cmd As String = Application.StartupPath & "\Tools\unzip.exe"
Dim arg As String = "-o """ & updateFileNameTarget & """"
Process.Start(cmd, arg)
End Sub
End Class
If you're already process-invoking everything else (including unzip), also use Sysinternal's streams.exe. Use the -d flag to remove the NTFS alternate data streams (ADS). There should only be one - and it is the one that indicates to Windows that the file was downloaded from an "untrusted source".
Your downloaded files will currently have a stream that looks like this:
:Zone.Identifier:$DATA 26
Remove this stream from the download files after extracting but before execution, and the warning will no longer appear.
See also: What is Zone Identifier? - and Accessing alternate data streams in files for a library to work with these within .NET without needing streams.exe.

How to make my program run at startup?

I'm programming a desktop application similar to Google desktop but with my own gadget with vb.net 2008 how can i make my application when the user install it on their computer to run at the time of start up?
Let assume that my application name is windowsAplication1 and I'm using windows XP and the program will be installed on C drive?
You can add it to registry with the following code
My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue(Application.ProductName, Application.ExecutablePath)
you can remove it using
My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).DeleteValue(Application.ProductName)
The above code will add it to all users. You can add it to current user in the following key
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Or you can add a link to your application in the "Startup" folder.
I suggest you dont do it automatically it may irritate the user. I hate when apps add them automatically to Windows Startup. Give an option for the user to run the program on windows startup.
Simpley use this code:
Dim info As New FileInfo(application.startuppath)
info.CopyTo(My.Computer.FileSystem.SpecialDirectories.Programs + "\startup\myapp.exe")
hope it helps.
You Can Do this Using the code below
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' This is where you'll need to have the program
' set the check box to the previous selection that
' the user has set. It's up to you how you do this.
' For now, I'll set it as "unchecked".
CheckBox1.Checked = False
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' The following code is a rendition of one provided by
' Firestarter_75, so he gets the credit here:
Dim applicationName As String = Application.ProductName
Dim applicationPath As String = Application.ExecutablePath
If CheckBox1.Checked Then
Dim regKey As Microsoft.Win32.RegistryKey
regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
regKey.SetValue(applicationName, """" & applicationPath & """")
regKey.Close()
Else
Dim regKey As Microsoft.Win32.RegistryKey
regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
regKey.DeleteValue(applicationName, False)
regKey.Close()
End If
' Assuming that you'll run this as a setup form of some sort
' and call it using .ShowDialog, simply close this form to
' return to the main program
Close()
End Sub
Imports Microsoft.Win32
...
Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", Application.ProductName, Application.ExecutablePath, RegistryValueKind.String)
A simple method
Imports Microsoft.Win32
...
Dim regKey As RegistryKey
regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run",True)
regKey.SetValue(Application.ProductName, Application.ExecutablePath)
regKey.Close()
Hope it helps
Just try this code :-
FileCopy("Name.Ext", Environment.GetFolderPath(Environment.SpecialFolder.Startup) & "\Name.Ext")
Here (Name.Ext) :-
Name - Your Application's name.
Ext - The Extension, it's of-course .exe
It's the simplest and best to use.
Might be old topic but adding
Imports System.Security.AccessControl.RegistryRights
Should resolve System.Security.SecurityException: 'Requested registry access is not allowed.' trouble stated by Christhofer Natalius