Show a WinForms from a Console application - vb.net

I have an existing Console Application project.
I have added a Windows Form to the project called myForm
When the project runs it goes to the Console's Main method - in this method how do I activate/show myForm ?
I assume I need to import the library System.Windows.Forms so the top of my console code looks like the following:
Imports System.Windows.Forms
Module Module1
Sub Main()
myForm. '<<<<not sure how to activate form
...

You have to add the reference System.Windows.Forms, and then show the form:
myForm.Show()
Or
myForm.ShowDialog()
myForm has to be a Form type. Maybe you need to instanciate you form first:
Dim myForm as new FormName

Try this:
Sub Main()
'Your code goes here...
System.Windows.Forms.Application.Run(New myForm)
'Your code goes here...
End Sub

No need to import the forms library (I've tested) and the working code that I now have is:
My main problem was not declaring and creating an instance of the windows form.
Module Module1
Sub Main()
Dim xForm As myForm = New myForm
xForm.ShowDialog()

Call this function.
Application.Run(myForm)
It runs even from the console app.
From the documentation,
Begins running a standard application message loop on the current thread, and makes the specified form visible.
EDIT: Declare it like this.
Public Class MyForm
Inherits Form
' Make the code here
End Class
Dim form As MyForm = New MyForm
Application.Run(form)

Related

how to pass commandlinearguments from to a Running Application [duplicate]

I have already implemented context menu to appear when a user right-clicks a file in windows explorer using Registry. The file address will be passed to the application as command lines. Parsing it is no problem.
How can I implement that is similar to "Add To Windows Media Player Playlist"? It does not open another instance of the app but works on the same open window and adds it to a list?
There are 2 ways to do this depending on how your app starts.
Method 1: Using VB App Framework and a MainForm
This is the easiest because you mainly just need to add some code for an Application event. First, add a method to your main form to receive new arguments from subsequent instances of your app:
Public Class MyMainForm ' note the class name of the form
...
Public Sub NewArgumentsReceived(args As String())
' e.g. add them to a list box
If args.Length > 0 Then
lbArgs.Items.AddRange(args)
End If
End Sub
Next:
Open Project Properties
Check the "Make Single Instance" option
At the bottom, click View Application Events
This will open a new code window like any other; Select MyApplication Events in the left drop down; and StartupNextInstance in the right one.
Here, we find the main form and send the command line arguments to the method we created:
Private Sub MyApplication_StartupNextInstance(sender As Object,
e As ApplicationServices.StartupNextInstanceEventArgs) _
Handles Me.StartupNextInstance
Dim f = Application.MainForm
' use YOUR actual form class name:
If f.GetType Is GetType(MyMainForm) Then
CType(f, MyMainForm).NewArgumentsReceived(e.CommandLine.ToArray)
End If
End Sub
Note: Do not try to fish the main form out of Application.OpenForms. A few times I've had it fail to find an open form in the collection, so I have quit relying on it. Application.MainForm is also simpler.
That's it - when a new instance runs, its command line args should be passed to the form and displayed in the listbox (or processed however your method sees fit).
Method 2: Starting From Sub Main
This is more complicated because starting your app from a Sub Main means that the VB Application Framework is not used, which provides the StartupNextInstance event. The solution is to subclass WindowsFormsApplicationBase to provide the functionality needed.
First, give your main form a meaningful name and add something like the NewArgumentsReceived(args As String()) as above.
For those not aware, here is how to start your app from Sub Main():
Add a module named 'Program' to your app
Add a Public Sub Main() to it.
Go to Project -> Properties -> Application
Uncheck Enable Application Framework
Select your new "Sub Main" as the Startup Object
The module can actually be named anything, Program is the convention VS uses for C# apps. The code for Sub Main will be later after we create the class. Much of the following originated from an old MSDN article or blog or something.
Imports Microsoft.VisualBasic.ApplicationServices
Imports System.Collections.ObjectModel
Public Class SingleInstanceApp
' this is My.Application
Inherits WindowsFormsApplicationBase
Public Sub New(mode As AuthenticationMode)
MyBase.New(mode)
InitializeApp()
End Sub
Public Sub New()
InitializeApp()
End Sub
' standard startup procedures we want to implement
Protected Overridable Sub InitializeApp()
Me.IsSingleInstance = True
Me.EnableVisualStyles = True
End Sub
' ie Application.Run(frm):
Public Overloads Sub Run(frm As Form)
' set mainform to be used as message pump
Me.MainForm = frm
' pass the commandline
Me.Run(Me.CommandLineArgs)
End Sub
Private Overloads Sub Run(args As ReadOnlyCollection(Of String))
' convert RO collection to simple array
' these will be handled by Sub Main for the First instance
' and in the StartupNextInstance handler for the others
Me.Run(myArgs.ToArray)
End Sub
' optional: save settings on exit
Protected Overrides Sub OnShutdown()
If My.Settings.Properties.Count > 0 Then
My.Settings.Save()
End If
MyBase.OnShutdown()
End Sub
End Class
Note that the three main things the App Framework can do for us ("Enable XP Styles", "Make Single Instance" and "Save Settings on Exit") are all accounted for. Now, some modifications to Sub Main:
Imports Microsoft.VisualBasic.ApplicationServices
Imports System.Collections.ObjectModel
Module Program
' this app's main form
Friend myForm As MyMainForm
Public Sub Main(args As String())
' create app object hardwired to SingleInstance
Dim app As New SingleInstanceApp()
' add a handler for when a second instance tries to start
' (magic happens there)
AddHandler app.StartupNextInstance, AddressOf StartupNextInstance
myForm = New MyMainForm
' process command line args here for the first instance
' calling the method you added to the form:
myForm.NewArgumentsReceived(args)
' start app
app.Run(myForm)
End Sub
' This is invoked when subsequent instances try to start.
' grab and process their command line
Private Sub StartupNextInstance(sender As Object,
e As StartupNextInstanceEventArgs)
' ToDo: Process the command line provided in e.CommandLine.
myForm.NewArgumentsReceived(e.CommandLine.ToArray)
End Sub
End Module
The SingleInstanceApp class can be reused with any Sub Main style app, and the code in that method is mainly a copy-paste boilerplate affair except for perhaps the form reference and actual name of the NewArgumentsReceived method.
Testing
Compile the app, then using a command window, send some commandline arguments to the app. I used:
C:\Temp>singleinstance "First Inst" apple bats cats
This starts the app as normal, with the arguments shown. Then:
C:\Temp>singleinstance "Next Inst" ziggy zoey zacky
C:\Temp>singleinstance "Last Inst" 111 222 3333
It doesnt matter which approach you use - they both work the same. The Result:
Note that depending on security settings, your firewall may request permission for apps using either method to connect to other computers. This is a result of how an instance sends or listens for the arguments from others. At least with mine, I can deny permission to connect and everything still works fine.
#Plutonix solution is quite efficient and elegant.
However if you program goes through multiple Forms i.e. if the Main Form can change during program execution, for example if you have a login form and then a main form, or a sequence of non-modal forms, Application.MainForm won't always be the same form and may not be known beforehand (hard coded).
Plutonix code assumes it is known and hard codes it.
In this case, you may want to be able to receive the NewArguments at all times, in whichever form is active at the time in your application.
There are 2 solutions to extend Plutonix solution:
1) Repeatedly force Application.MainForm to a specific form in code (I haven't tested this but Application.MainForm is Read/Write so it could work).
2) The most elegant is to implement an Interface on all forms that can possibly become the MainForm:
Create the Basic interface:
Public Interface INewArgumentsReceived
Sub NewArgumentsReceived(args As String())
End Interface
Modify #Plutonix code for MyApplication_StartupNextInstance to:
Private Sub MyApplication_StartupNextInstance(sender As Object, e As ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
Dim f = Application.MainForm
If f.GetType.GetInterfaces.Contains(GetType(INewArgumentsReceived)) Then
CType(f, INewArgumentsReceived).NewArgumentsReceived(e.CommandLine.ToArray)
Else
MsgBox("The current program state can't receive new requests.",, vbExclamation)
End If
Now on all possible forms that can become the Main Form, implement the INewArgumentsReceived Interface:
Public Class FormA: Implements INewArgumentsReceived
Public Sub NewArgumentsReceived(args As String()) Implements INewArgumentsReceived.NewArgumentsReceived
MsgBox("Got new arguments")
End Sub
The other advantage of using the Interfaces is that we can check if the current Application.MainForm implements it and is able to receive it.
If the current Application.MainForm does not implement the Interface it fails gracefully with an informational message.

VB.NET: How to control the Form that is displayed when the program starts from Sub Main

VB.NET 2012
My Startup Object is set to (Sub Main). The app needs to collect a few different sets of data before the primary form is loaded
This article http://msdn.microsoft.com/en-us/library/ms235406(v=vs.110).aspx mentions
In Main, you can determine which form is to be loaded first when the program starts
But it never explains how to show the form
If I use ShowDialog the application terminates when mainView’s Visible property is set to False or when mainView is Hidden
Module Module1
Public mainView As New Form1
Public Sub Main()
' initialization code
mainView.ShowDialog() ' this works until I need to hide mainView, ShowDialog returns and the app terminates
End Sub
End Module
If I use Show the application immediately falls out of Sub Main and terminates
Module Module1
Public mainView As New Form1
Public Sub Main()
' initialization code
mainView.Show() ' this doesn't work at all, the app terminates as soon as Main is executed
End Sub
End Module
The primary form needs to exist the entire time the app is running.
I need sections of code to run before the primary form is displayed.
I need to be able to hide the primary at times and show it at others.
What is the best approach to achieve these requirements?
This seems to work perfectly. I had read about the messaging loop but it didn’t seem to work until I tried it like below, thanks LarsTech
Module Module1
Public mainView As Form1
Public Sub Main()
' initialization code
''...
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
mainView = New Form1
Application.Run(mainView) ' I can reference 'mainView' from anywhere in my app, toggle its Visible property etc.
End Sub
End Module

Using button.enabled outside the Button_Click sub

I am just starting out with Visual basic .Net. I am designing an application where each button should disable itself after a registering a single click on it.
I am trying to add an additional sub, which when called, disables all of the buttons. (Disable_all())
Public Sub disable_all()
MsgBox("Testing disable_all")
Button_eight.Enabled = False
End Sub
One of the subs is calling it from the main module.
Private Sub disable()
Dim variab As Form1 = New Form1
variab.disable_all()
End Sub
The disable_all() sub however does not disable Button_eight when called. I placed a message box to check if the sub (disable_all) is getting executed, which it is. I get a message box having the text "Testing disable all" but the Button_eight is not disabled for some weird reason.
I'd really appreciate some help, thanks.
It's simple, just do Form1.disable_all().
That is, instead of variab.disable_all(), call: form1.disable_all() from the main module. Because as mentioned in the comments, new form1 creates a new instance of Form1.
You can also create a variable that point to the form dim var = form1 or dim variab as form = form1, but since you can access form1 directly from your module, it is unnecessary.

How can I emulate a PictureBox control in a console application

Is there any way to emulate a picturebox in a console application? I tried this way but the image always returned completely black:
Using P As New PictureBox
P.Size = New Point(255, 255)
P.Image = New Bitmap(255, 255) 'I did set a real image, but I didn't for the sake this example
End Using
Assuming you've imported everything needed to show the form, don't use the form.Show method. Instead, use Application.Run(New Form1) to show the form. This post has a more complete answer.
You can design the form in the designer,use it as is, or declare it as a new object and change any properties and pass the new object to the Run method.
Imports System.Drawing
Imports System.Windows.Forms
Module Module1
Sub Main()
Dim newform1 As New Form1
newform1.PictureBox1.Image = New Bitmap("MyImageFile")
Application.Run(newform1)
Console.ReadLine()
End Sub
End Module

Delegates not working in another module

Running into an odd issue with tasks and delegates. Code in question is running under dotNET 4.5.1, VS2013. On the form's code I have a sub that updates a grid, it checks to see if an invoke is required, and if it is it calls a delegate. When a task runs that's called in the same module, it works as expected, no problems. Threaded or not, the grid updates properly.
However, if the same thing is called from another module, the delegate never gets called and the visual component doesn't get updated. Just a watered down bit of pseudocode to clarify..
In the form's module:
Private Delegate Sub DoWhateverDelegate(ByVal _____)
Public Sub DoWhatever(ByVal _____)
If MyComponent.InvokeReqired
Dim Delegated As New DoWhateverDelegate(AddressOf DoWhatever)
Debug.Print("The delegate fired")
Invoke(Delegated, _____)
Else
' .. carry on as usual ..
End If
End Sub
Elsewhere....
Task.Run(Sub()
' .. various things I'd rather not block the UI thread with ..
DoWhatever()
End Sub)
Works fine. I can do Task.Run__ that calls DoWhatever and it's all happy and good. However if I create a task in another module and call DoWhatever, it doesn't fire the delegate and that visual component doesn't update. The code is identical, in the same module it works, in another module it does not.
I'm probably missing something blatantly obvious.. anyone care to point out my mistake? Thanks.
Edit -- just to clarify, that other module is just code, there's only one form in the entire solution. It's created at program startup automatically, there is no other form creation going on.
Should be a thread-specific issue. Check this:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
foo.DoSomething()
End Sub
End Class
The class with the delegate:
Public Class foo
Public Shared Sub DoSomething()
Task.Run(Sub() UpdateText())
End Sub
Public Delegate Sub UpdateTextDelegate()
Public Shared Sub UpdateText()
Dim f = Form1
'Dim f As Form1 = Application.OpenForms("Form1")
If f.InvokeRequired Then
Dim d As UpdateTextDelegate = AddressOf UpdateText
f.Invoke(d)
Else
f.TextBox1.Text = "Hi"
End If
End Sub
End Class
Run the code and the textbox will not be updated. Use the second f=.... (that one that take a reference from OpenForms) and it will be updated.
If you just try to access the default instance and you are outside the UI-thread, a new instance of the form will be created. That means, the content IS updated, but because that form is not shown, you will not see it.
NOTE I do NOT advise to solve your problem, by using OpenForms. I'd advise to correctly instantiate forms!
Add a new module/class to your code:
Module Startup
Public MyForm1 As Form1
Public Sub main()
MyForm1 = New Form1
Application.Run(MyForm1)
End Sub
End Module
Go to project properties -> application. Disable application framework and choose Sub Main as your start object. In the app, access your form via MyForm1 - or whatever you want to name it. Problem should be gone then.