I have a vb.net winforms project and after opening a form that has code that has the following line
Dim ChildForm As frmItemInstallation = New frmItemInstallation
I am getting the following error message:
Overload resolution failed because no accessible 'New' is most specific for these arguments: 'Public Sub New()': Not most specific. 'Friend Sub New()': Not most specific
I wasn't getting this in the past, just started when I reopened the project to make changes
this is on an existing form in the project, if I create a new form, I don't get the error message
I am using VS 2017 runtime is 4.6.1
Any help would greatly be appreciated
Public Class frmInventory
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
Related
I would like to ask if someone can help me with this.
I have this code that Unload a CorelDRAW Macro project a get the new one from the network in order to became easier to update several machines.
VBA code:
Sub CDRMacroUpdate()
' Unloads the project from CorelDRAW
GMSManager.Projects("Project1").Unload
Dim nMacro As String
' The project have the same name, but it's a new file, here is in the C drive, but it's located in the network folder
nMacro = "C:\Project1.gms"
' Loads the new file and copy to the User GMS folder
GMSManager.Projects.Load nMacro, True, False
End Sub
Now I'm trying to convert this VB.Net but I'm getting a lot of errors and I can't see what I'm doing wrong.
In a form with a Button I have this code:
I'm using SharpDevelop
Imports Corel.Interop.VGCore
Public Partial Class MainForm
Public Sub New()
' The Me.InitializeComponent call is required for Windows Forms designer support.
Me.InitializeComponent()
End Sub
Sub BtnUpdateMacroClick(sender As Object, e As EventArgs)
Dim GMSManager As Corel.Interop.VGCore.GMSManager
GMSManager.Projects("Project1").Unload
Dim nMacro As String
nMacro = "C:\Project1.gms"
GMSManager.Projects.Load(nMacro, True, False)
End Sub
End Class
Now, can someone please explain what I'm doing wrong in the VB.Net code?
Thank very much for the help.
I am creating a application to be used with a touch panel device. The touch panel device comes with a standard windows OSK (On screen Keyboard). Whilst testing its been concluded that the standard OSK is to large and too complex for what we need it in. So I have built my own OSK. some of the feilds though only requier numeric inputs so I though of futher simplifying the process by creating a new form which hosts a numeric pad. so far this is all working. the idea is then to have the app which ask for diffrent inputs then to trigger the OSK application, say that the user wants to enter a phonenumber in one textbox I then want to start the OSK app using a parameter that trigers the OSK to start the NumericForm form first... this too I have working but the thing I can't get right is to hide the AlphabetForm I have tried the following method but am a little stumpt on how to get this right
In short its the Me.hide which isnt working as expected?
Private Sub AlphabetForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
#Region "Recive startup parameters (if any)"
Try
Dim OSKParameters As String = Command()
If OSKParameters = "OSKNUM" Then
NumericForm.Show()
Me.Hide()
Else
ShiftSelect = 0
End If
Catch ex As Exception
'Do nothing
End Try
#End Region
End Sub
Three possible setups, as described in comments:
► Using the Application Framework, override OnStartup and set Application.MainForm to a Form object determined by a command-line argument:
To generate ApplicationEvents.vb, where Partial Friend Class MyApplication is found, open the Project properties, Application pane, click the View Application Events Button: it will add the ApplicationEvents.vb file to the Project if it's not already there.
Imports Microsoft.VisualBasic.ApplicationServices
Partial Friend Class MyApplication
'[...]
Protected Overrides Function OnStartup(e As StartupEventArgs) As Boolean
Application.MainForm = If(e.CommandLine.Any(
Function(cmd) cmd.Equals("OSKNUM")), CType(NumericForm, Form), AlphabetForm)
Return MyBase.OnStartup(e)
End Function
'[...]
End Class
► Disabling Application Framework, to start the Application from Sub Main().
In the Project->Properties->Application pane, deselect Enable application framework and select Sub Main() from the Startup form dropdown.
If Sub Main() doesn't exist yet, it can be added to a Module file. Here, the Module is named Program.vb.
Module Program
Public Sub Main(args As String())
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(True)
Dim startForm as Form = If(args.Any(
Function(arg) arg.Equals("OSKNUM")), CType(New NumericForm(), Form), New AlphabetForm())
Application.Run(startForm)
End Sub
End Module
► If the OSK can be moved to UserControls, similar to what jmcilhinney suggested, run the default container Form and select the UserControl to show using the same logic (inspecting the command-line arguments):
Public Class AlphabetForm
Public Sub New()
InitializeComponent()
Dim args = My.Application.CommandLineArgs
Dim uc = If(args.Any(
Function(arg) arg.Equals("OSKNUM")), CType(New NumericUC(), UserControl), New AlphabetUC())
Me.Controls.Add(uc)
uc.BringToFront()
uc.Dock = DockStyle.Fill
End Sub
End Class
I have another issue:
I am able to build my VB.NET application. However, when I go to debug it, I get an unhandled exception:
System.InvalidOperationException occurred HResult=0x80131509
Message=An error occurred creating the form. See
Exception.InnerException for details. The error is: Object reference
not set to an instance of an object. Source=ProovePC StackTrace:
at ProovePC.My.MyProject.MyForms.Create__Instance__[T](T Instance) in
:line 190 at ProovePC.My.MyProject.MyForms.get_Front1() at
ProovePC.My.MyApplication.OnCreateMainForm() in
C:\Users\Phillip\source\Workspaces\Upwork
Projects\ProoveIt\ProovePC\My Project\Application.Designer.vb:line 35
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine) at ProovePC.My.MyApplication.Main(String[] Args) in
:line 81
Inner Exception 1: NullReferenceException: Object reference not set to
an instance of an object.
The odd part is that it occurs in auto-generated code, in the Application.Designer.vb file. I have confirmed that the constructor is public and that the name of the form matches the name within this file:
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = true
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterAllFormsClose
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.ProovePC.Front1 'Error occurs here?
End Sub
End Class
End Namespace
I am a little lost on this since I am new VB.NET, but I would like to think that the fix is a simple one. For those wondering, I am running visual studio 2017. I should note that I come from a C# background and recently got into vb.net. So please, explain as much as possible.
Edit:
Form Constructor:
Public Sub New()
' This call is required by the designer.
'NewMethod()
InitializeComponents()
' Add any initialization after the InitializeComponent() call.
End Sub
Edit:
Ok so here is the interesting part, now I am getting the error on the InitializeComponents function itself within the auto generated constructor of the form. Once I comment this function out, I am able to build and run the application. I only get so far because that application needs hardware to fully run which I have not connected yet.
Now, here is the interesting part, if I were to comment out the constructor, there is a line above it that comes back as undefined reference error:
Public MainStatus As StatusStrip = StatusStrip1 'Error is here now
'Public Sub New()
' This call is required by the designer.
'InitializeComponent()
' Add any initialization after the InitializeComponent() call.
'End Sub
For those wondering, I am now in the front1.vb file
there was a property within the form control that was being set to nothing when it needs to be set to Me.
As for the random line of code, Public MainStatus As StatusStrip = StatusStrip1 I think that it was accidentally copy pasted there as the variable is only used at that line. I commented it out and everything builds good now.
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.
I can't figure out what the issue is here. I started project from scratch, went to debug, and received error:
System.InvalidOperationException was unhandled Message=An error
occurred creating the form. See Exception.InnerException for details.
The error is: Object reference not set to an instance of an object.
I am not understand why this error is occurring in an auto-generated file. Here is the code in it's entirety:
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.269
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.AccountAndClientFull.frmMain 'HERE IS WHERE THE ERROR OCCURS
End Sub
End Class
End Namespace
Error occurs at:
Me.MainForm = Global.AccountAndClientFull.frmMain
Any suggestions? I can't figure out what changes need to be made in the application tab of the project properties.
I got the same error and realized it was because I had declared a private default constructor in the form code. If you created a constructor and didn't make it public, try making it public.
Make sure you have a Form Class called frmMain, attention not the file name but the Class Name.
Maybe you have renamed the Form file name to frmMain.vb but in the code of the file the signature of the class remains different.
Another possible cause of this error is if an exception occours in the event handlers of the controls of the forms during initialization.
The creation of the form fails and so an exception is raised.
Another possible cause of this symptom, and a particularly obscure one:
I added two LineShape controls to a child form in Designer and it caused the Me.MainForm error.
(Toolbox/Visual Basic PowerPacks/LineShape).
This point in the documentation may provide a clue:
"When you create a LineShape control at run time, you must also create a ShapeContainer and set the Parent property of the LineShape to the ShapeContainer."
I added the LineShapes using designer so it should have created the ShapeContainers automatically but that may have failed, perhaps because I added them inside a container several layers deep already. I removed the LineShapes to resolve the issue.
If you have any criteria directly under the class that causes an error, it will also break on this error.
For example:
Public Class Form1
Dim FILE_NAME As String = "C:\Folder\File.txt" '//if this file does not exist
Dim objReader As New System.IO.StreamReader(FILE_NAME)
This last line will cause an error in Protected Overrides
I didn't like VB.NET feature when carriage return from string, so added this code under Public Class Form1 in hope to remove that annoying one:
Dim origString As String
Dim newString As String = origString.Replace(vbCr, "").Replace(vbLf, "")
This code caused a same problem. So possible solution is to comment or remove it:
'Dim origString As String 'From Multiline Textbox'
'Dim newString As String = origString.Replace(vbCr, "").Replace(vbLf, "")
I had the same problem... i deleted all the tools in my form and then it ran without any issue... then i found out that it was the webbrowser control that caused me the problem... i deleted it and added it again and the program ran without any trouble... try removing controls one by one and check which one causing the problem... then delete the particular control and re-add it to make it work... this happens when you copy your solution from one pc to another...
Public Sub New()
InitializeComponent()
End Sub
JUST ADD THIS CODE TO YOUR FORM
frmMain
I actually had this error when I ADDED the following to my Form.
Private Sub New()
InitializeComponent()
End Sub
Very strange!