I'm doing a VB.NET WPF application using VS2013, and I am just trying to find and use the right entry point.
I have read tons of answers on this, one saying something and the other saying the opposite. Mainly they say: the entry point of your project is the autogenerated main() you can find in your Application.g.vb. Yes, ok, very nice but...it is a generated file, not a good idea to modify it. So I searched the net on how to implement my own main() method, and the common answer I've found is:
Select Application.xaml and change its build action to "Page"
Create your own main method in Application.xaml.vb with this signature:
_
Public Shared Sub Main()
Dim app As Application = New Application()
app.InitializeComponent()
app.Run()
End Sub
Go to your project properties, untick "Enable applpication framework" and select Sub Main as startup for your application.
And so I have done but I continuously get this error:
Error 3 Class 'Application' must implement 'Sub InitializeComponent()' for interface 'System.Windows.Markup.IComponentConnector'.
this is the Application.g.i.vb file it generates:
#ExternalChecksum("..\..\Application.xaml","{406ea660-64cf-4c82-b6f0-42d48172a799}","DB788882721B2B27C90579D5FE2A0418")
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
Imports System
Imports System.Diagnostics
Imports System.Windows
Imports System.Windows.Automation
Imports System.Windows.Controls
Imports System.Windows.Controls.Primitives
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Ink
Imports System.Windows.Input
Imports System.Windows.Markup
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Media.Effects
Imports System.Windows.Media.Imaging
Imports System.Windows.Media.Media3D
Imports System.Windows.Media.TextFormatting
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Imports System.Windows.Shell
'''<summary>
'''Application
'''</summary>
<Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Public Class Application
Inherits System.Windows.Application
Implements System.Windows.Markup.IComponentConnector
Private _contentLoaded As Boolean
'''<summary>
'''InitializeComponent
'''</summary>
<System.Diagnostics.DebuggerNonUserCodeAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")> _
Public Sub InitializeComponent()
#ExternalSource("..\..\Application.xaml",4)
Me.StartupUri = New System.Uri("MainWindow.xaml", System.UriKind.Relative)
#End ExternalSource
If _contentLoaded Then
Return
End If
_contentLoaded = True
Dim resourceLocater As System.Uri = New System.Uri("/FatLink;component/application.xaml", System.UriKind.Relative)
#ExternalSource("..\..\Application.xaml",1)
System.Windows.Application.LoadComponent(Me, resourceLocater)
#End ExternalSource
End Sub
<System.Diagnostics.DebuggerNonUserCodeAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0"), _
System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never), _
System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes"), _
System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity"), _
System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")> _
Sub System_Windows_Markup_IComponentConnector_Connect(ByVal connectionId As Integer, ByVal target As Object) Implements System.Windows.Markup.IComponentConnector.Connect
Me._contentLoaded = True
End Sub
End Class
so...as Sub InitializeComponent() is there, why the hell do I keep getting this error?
**EDIT:**My Application.xaml.vb is just that:
Partial Public Class Application
<System.STAThreadAttribute(), _
System.Diagnostics.DebuggerNonUserCodeAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")> _
Public Shared Sub Main()
Dim app As Application = New Application()
app.InitializeComponent()
app.Run()
End Sub
End Class
I have managed to reproduce you problem:
Create a new WPF VB.NET application
Create the custom Main in the Application.xaml.vb file as from your post
In the project properties uncheck the Enable Application Framework (automatically the startup object becomes our Main sub)
Set for the Application.xaml file the Build Action property to Page
At this point, the line that call app.InitializeComponent() is underlined with a red squiggle to signify that the project cannot find the InitializeComponent method. If you try to compile at this point you get the mentioned error.
Final step:
In Application.xaml file remove the
StartupUri="MainWindow.xaml"
Now the squiggle disappears and the compilation ends correctly.
If you want to start you own main window you could change the Run line with
app.Run(New MainWindow())
If you get that error, you probably haven't stated that your app is to start with your Main() method. So:
"Go to your project settings and untick the Enable application framework checkbox (if it's ticked) and select Sub Main as the Startup object , then add your main-method to Application.xaml.vb (plus the logger and other stuff)."
When you have done that, VS won't create "its own" Main-method and will rather call the one you defined in Application.xaml.
Taken from: https://social.msdn.microsoft.com/Forums/vstudio/en-US/d7ef493f-27be-4f32-8ff4-a014078f572c/custom-systemwindowsapplication-in-vb-net?forum=wpf
Check also this: http://ugts.azurewebsites.net/data/UGTS/document/2/3/32.aspx
Related
I have created a DLL in VB.NET and loaded in VB6.
All variables and methods are working very well.
In the DLL, I have a RaiseEvent.
The RaiseEvent from .NET DLL cannot trigger the methods in VB6.
Option Explicit On
Option Strict On
Imports System.Windows.Forms
Imports System.Net.Sockets
Imports System.IO
Imports System.Text
Imports System.Net
Imports System.ComponentModel
Imports System.Threading
Imports System.Runtime.InteropServices
<ComClass(TestDLL.ClassId, TestDLL.InterfaceId, TestDLL.EventsId)>
Public Class TestDLL
Public Const ClassId As String = "6E9AB173-14BD-4DE4-9AE0-A9638FCE40B3"
Public Const InterfaceId As String = "E659D166-F952-489F-899F-0104553B44E4"
Public Const EventsId As String = "1C38AB4A-84B9-4CC2-A090-0C272177ECED"
Public Event Disconnected()
Public Event FirstConnect()
Public Event Waagerecht()
Private Sub Received(ByVal msg As String) Handles Me.Receive
RaiseEvent Waagerecht()
End Sub
This DLL is working in C#, VB.NET and in Labview amazing. Only not in VB6
RaiseEvent Part in VB.NET DLL
And the code in VB6:
Option Explicit
Private WithEvents MyNetClass As TestDll
Private Sub Form_Load()
Set MyNetClass = New TestDll
End Sub
Private Sub Form_Terminate()
Set MyNetClass = Nothing
End Sub
And the methods for triggering:
Private Sub MyNetClass_Waagerecht()
MsgBox "Ich werde angezeigt, sobald dll mir was sagt"
End Sub
Disclaimer: The following is based on issues I have experienced with Office VBA and events being raised on a secondary thread. Due to their similar underlying architecture, I am assuming that VB6 will have similar issues. I do not have VB6 so I can not verify the this.
With that stated, it appears that your code is using NetworkStream.BeginRead and the callback events will arrive on a secondary thread, you may be experiencing problems due to the event being raised on the secondary thread.
To provide thread synchronization to the COM class, I utilize a System.Windows.Forms.Control. The control is created in the class constructor to capture the thread it is created on. Events are defined as Custom Event so that the RaiseEvent method can be defined to use the InvokeRequired property of the synchronizing control. I have only shown the pattern for your Waagerecht event; if this works, you will need to implement the same pattern for your other Public events.
Private synch As ISynchronizeInvoke
Public Sub New()
Dim marshalingControl As New System.Windows.Forms.Control
marshalingControl.CreateControl() ' the handle must be created
synch = marshalingControl
End Sub
Private _Waagerecht As Action
Public Custom Event Waagerecht As Action
AddHandler(value As Action)
_Waagerecht = CType([Delegate].Combine(_Waagerecht, value), Action)
End AddHandler
RemoveHandler(value As Action)
_Waagerecht = CType([Delegate].Remove(_Waagerecht, value), Action)
End RemoveHandler
RaiseEvent()
If _Waagerecht IsNot Nothing Then
If synch.InvokeRequired Then
synch.Invoke(_Waagerecht, {})
Else
_Waagerecht.Invoke()
End If
End If
End RaiseEvent
End Event
Edit: Recommendations For Debugging
A first step add the following to the VB.Net TestDLL class.
Public Sub TestWaagerecht()
RaiseEvent Waagerecht()
End Sub
Then in your VB6 code, add a button to your form and in its Click handler, call MyNetClass.TestWaagerecht. This will verify whether or not the VB6 code is receiving the event.
Hopefully this will work with VB6. Try setting up VB.Net project for debugging. If the project does not have an app.config, add one (Project Menu->Add New Item->"Application Configuration File"). I don't know why, but without the app.Config file, break-points are not hit.
Next go to Project Properties->Debug Tab and set the "Start External Program" to point to the VB6 program. Add a break-point in the Sub TestWaagerecht that I asked you to add above.
When you click on the "Start" button in VS to start debugging, it should launch VB6. Now load your VB6 project and start debugging it. Click on the button that calls TestWaagerecht. Hopefully, the VS break-point will be hit. If it is hit, then all is well and you can start debugging your code to hopefully find the issue.
When typing code in Visual Studio 2015 it automatically gives me alternatives on what I can do with my code:
I was wondering if there is a way to enable autocomplete on imported Objects / Libraries (.dll) files?
I am using IBM 3270 and have imported all of the libraries and added them as references to my project, but I still don't get any alternatives.
Here is an example of the code and what I believe it should do:
' The Imports are already referenced to the project.
' I have added them here to visually display that I am using the libraries.
Imports AutConnListTypeLibrary
Imports AutConnMgrTypeLibrary
Imports AutOIATypeLibrary
Imports AutPSTypeLibrary
Imports AutSystemTypeLibrary
Public Class IBM3270
Public Shared autECLConnList As Object
autECLConnList = CreateObject("PCOMM.autECLConnList")
autECLConnList. ' <- I believe that I should get autocomplete words here, but I don't.
' Some of the alternatives that should pop up are:
' autECLConnList.Count
' autECLConnList.Refresh
End Class
Link to IBM Knowledge Center
EDIT: I have rewritten the code and the Autocomplete words appears, but I can't figure out how I can execute it now. Previously I used CreateObject("PCOMM.autECLConnList") to access the object.
Here is what I have:
Imports AutConnListTypeLibrary
Public Class IBM3270
Implements AutConnList
Default Public ReadOnly Property ConnInfo(Index As Object) As Object Implements IAutConnList.ConnInfo
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property Count As Integer Implements IAutConnList.Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Sub Refresh() Implements IAutConnList.Refresh
Throw New NotImplementedException()
End Sub
Public Shared Sub Test() ' Here is where I am stuck.
Dim autECLConnList As AutConnList ' I believe I can't reference AutConnList. ("PCOMM.autECLConnList") should probably be added someplace.
autECLConnList.Refresh
End Sub
End Class
I have created a "Empty Project(.NET Framework) Visual Basic"
I then added an empty Class object
Next I added the reference to System.Windows.Forms
And put the following code in the Class to make it an ApplicationContext
Imports System.Windows.forms
Public Class Class1
Inherits ApplicationContext
End Class
Lastly I tried setting the Startup Object to my Class1
However that is not an option ?
I tried adding a Sub Main to my Class1
but this had no effect
Imports System.Windows.forms
Public Class Class1
Inherits ApplicationContext
Sub main()
End Sub
End Class
At this point, hitting start fails with this error
Error BC30737 No accessible 'Main' method with an appropriate signature was found in 'Project4'.
At this point I could add a module with the following code
and that would compile without errors and run
Module Module1
Sub main()
End Sub
End Module
But that runs for an instant and terminates
In another similar program I have made, I know I could put the following code in a module instead
Module Module1
Public myClass1 As Class1
Sub main()
myClass1 = New Class1
Application.Run(myClass1)
End Sub
End Module
And that would run until I called Application.Exit()
However in this specific case, the Application Framework is disabled so this solution does not work.
So another solution I have found is to use Sleep(50) in a while loop
Imports System.Threading
Module Module1
Public myClass1 As Class1
Sub main()
While True : Thread.Sleep(50) : End While
End Sub
End Module
While I cannot find anything explicitly wrong with this, it strikes me as very inelegant.
It doesn't consume noticeable cpu time or memory
I just wonder if there isn't an equivalent way to do that using just ApplicationContext and dispose of the module entirely ?
If you have any suggestion I would love to hear them at this point.
I wrote this hoping to find a solution as I write the question but I am stuck at this point.
Where does the code go after Application.Run(myClass1)
It's probably looping something inoffensive while waiting for something to happen but what ?
thanks
Here is how to make the barest bone (console or non-console) application using the ApplicationContext Class.
In Visual Studio create a "Empty Project(.NET Framework) Visual Basic"
then add an empty class
Add the following reference by right-clicking on Reference in the Solution Explorer
System.Windows.Forms
Now paste the following code in your class
Imports System.Windows.Forms
Public Class Class1
Inherits ApplicationContext
Shared Sub Main()
Dim myClass1 As Class1
myClass1 = New Class1
System.Windows.Forms.Application.Run(myClass1)
End Sub
End Class
Now hit start and you've got a perfectly working useless application that does nothing with least amount of stuff that I could manage.
If you are here, I suspect that you also would like to manually compile this project from anywhere without having visual studio installed.
Very easy ! In your project folder, create a text file and rename it compile.bat
Paste this code in compile.bat
path=%path%;c:\windows\microsoft.net\framework\v4.0.30319
VBC /OUT:bin\Debug\app.exe /imports:System.Windows.Forms /T:winexe *.vb
pause
BONUS ROUND
This app does nothing, how do you know the events even work ?
Let's add, a tray icon, a resource file to add the tray icon and some events
First add a new reference to system.drawing
Go to project properties
Create a new resource file
Add some random *.ico file
Now replace the following code in the class
Imports System.Windows.Forms
Public Class Class1
Inherits ApplicationContext
Shared Sub Main()
Dim myClass1 As Class1
myClass1 = New Class1
System.Windows.Forms.Application.Run(myClass1)
End Sub
Private WithEvents Tray As NotifyIcon
Public Sub New()
Tray = New NotifyIcon
Tray.Icon = My.Resources.appico
Tray.Text = "Formless tray application"
Tray.Visible = True
End Sub
Private Sub AppContext_ThreadExit(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.ThreadExit
'Guarantees that the icon will not linger.
Tray.Visible = False
End Sub
Private Sub Tray_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Tray.Click
Console.WriteLine("Tray_Click")
End Sub
Private Sub Tray_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Tray.DoubleClick
Console.WriteLine("Tray_DoubleClick")
System.Windows.Forms.Application.Exit()
End Sub
End Class
And now, to compile this manually
First, find resgen.exe somewhere on your harddrive
and copy it in your "My Project" folder, you can probably download it from somewhere
Make sure you've got version 4 or above of resgen though
And overwrite the compile.bat with this new code
path=%path%;c:\windows\microsoft.net\framework\v4.0.30319
cd "My Project"
resgen /usesourcepath "Resources.resx" "..\bin\debug\Resources.resources"
cd ..
VBC /OUT:bin\Debug\app.exe /resource:"bin\debug\Resources.resources" /imports:System.Drawing,System.Windows.Forms /T:winexe *.vb "My Project\*.vb"
pause
Unfortunately, this last compile.bat doesn't work for me, it might work for you.
Mine compiles just fine, but the app crashes on start.
This worked in another project where I made the Resource files by hand but something is wrong with
I tried adding the root namespace to the build with /rootnamespace:Project5 but this had no effect
Still good enough for now, this last bit will be edited if a fix is ever found
I am working on a Visual Basic Project and i am getting stuck on something super simple. Unzipping a file.
I have the following imports
`Imports System.Net
Imports System
Imports System.IO
Imports System.IO.Compression`
My References are as follows
System
System.Core
System.Data
System.Data.DataSetExtensions
System.Deployment
System.Drawing
System.IO.Compression
System.IO.Compression.FileSystem
System.Net.Http
System.Windows.Forms
System.Xml
System.Xml.Linq
So what my code should be doing is checking if a software is installed,
if it is not it will download a zip file with the installed.
once the zip is downloaded it should extract it and run the setup.
Everything is working except this code block right here:
Private Sub client_OMSADownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
MessageBox.Show("Download Complete")
Try
ZipFile.ExtractToDirectory("C:\end.zip", "C:\end")
Catch ex As Exception
MsgBox("Can't Extract file" & vbCrLf & ex.Message)
End Try
End Sub
Public NotInheritable Class ZipFile
Public Shared Sub ExtractToDirectory(
sourceArchiveFileName As String,
destinationDirectoryName As String
)
End Sub
End Class
I get no exceptions, it just doesn't unzip, it basically skips right over the block.
Please help!
According your code, you have inherit the method ExtractToDirectory of ZipFile class that do nothing.
Public NotInheritable Class ZipFile
Public Shared Sub ExtractToDirectory(sourceArchiveFileName As String,
destinationDirectoryName As String)
End Sub
End Class
To solve this issue, simple delete this method from your code.
You're declaring ZipFile class yourself, while you should use existing one from System.IO.Compression namespace. So, just remove following part of your code:
Public NotInheritable Class ZipFile
Public Shared Sub ExtractToDirectory(
sourceArchiveFileName As String,
destinationDirectoryName As String
)
End Sub
End Class
...and everything should work as expected.
There is possibly a few things wrong with the below. Haven't had a chance to test/debug the code yet as can't run it. It stating that no main method has been found. But there is? i've even changed it to shared etc. It's probably something obvious?
It's flagging - 'Sub Main' was not found in 'ConsoleApplication1.Module1' error.
Also the main method wasn't always a separate class, I was just trying stuff. I'm importing a reference - system.processes. Was initially created as a vb.form but realised i didn't want the form part and recreated as a console app (which is very possibly where the problem lies as it's one of the first console apps i've done).
Code is basically planned to act on a service dying. Report and try and manage the restart (not finished, ideas welcome).
Imports System
Imports System.Management
Imports System.ServiceProcess
Imports System.Diagnostics
Imports System.Threading
Imports System.IO
Module Module1
Public Class Control
Public Sub Main() 'Public Sub Main(ByVal sArgs() As String)
Dim restart As New Rest
restart.startTime = DateTime.Now()
restart.cr20Services()
restart.Report()
End Sub
End Class
Public Class Rest
public startTime As String
Dim logPath As String = "C:\cr20\restart.txt"
'Dim fileExists As Boolean = File.Exists(strFile)
Dim arrcr20ServicesInitialStatus As New ArrayList
Dim failedServices As New ArrayList
Dim arrcr20Services As New ArrayList
Public Sub cr20Services()
'cr20 Services
arrcr20Services.Add("cr20 service")
arrcr20Services.Add("cr20 router")
For Each cr20Service In arrcr20Services
arrcr20ServicesInitialStatus.Add(cr20Service & " - " & cr20Status(cr20Service))
cr20Restore(cr20Service)
Next
End Sub
Private Function cr20Status(ByVal cr20Service As String)
Dim service As ServiceController = New ServiceController(cr20Service)
Return service.Status.ToString
End Function
Private Sub cr20Restore(ByVal cr20Service As String)
Dim service As ServiceController = New ServiceController(cr20Service)
'Dim p() As System.Diagnostics.Process = System.Diagnostics.Process.GetProcessesByName("calc")
If (service.Status.Equals(ServiceControllerStatus.Stopped)) Or (service.Status.Equals(ServiceControllerStatus.StopPending)) Then
failedServices.Add(service)
service.Stop()
Thread.Sleep(10000) 'give service 10 seconds to stop
service.Start()
End If
End Sub