Reputation: 15807
There is some code in an ASP.NET web application code behind class that I want to reuse in a VB.NET WinForms application. Please see the code below from the code behind (ASP.NET web application (not website)):
Public Class _Default
Inherits System.Web.UI.Page
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
MsgBox("button1.click")
End Sub
End Class
and the code behind:
Imports WebApplication1
Public Class TestClass
Public Shared Sub Test100()
MsgBox("button clicked on page")
End Sub
End Class
Public Class Form1
Public Event BellRings(ByVal sender As Object, ByVal e As EventArgs)
Public test As String
public Shared TestMethod()
MsgBox("Test Method was called")
End public
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Try
Dim d As WebApplication1._Default = New WebApplication1._Default
AddHandler d.button1.Click, AddressOf Form1.TestMethod
Catch ex As Exception
End Try
End Sub
End Class
I realise that it would probably be better to create a service layer, which both clients use, however I am wandering if the above is even possible? i.e. is it possible to add an event handler in a WinForm for an event in a web application i.e. button.click?
Upvotes: 0
Views: 1020
Reputation: 44931
You could potentially get away with this through the creative use of partial classes and referencing the code-behind class from the winforms app.
However, that would be a very fragile implementation. For example, if you wanted to provide the same functionality through a menu or want to change the button control to a third-party vendor's control that does not have the same signature as the winforms control or vice versa.
A much better approach, even without the service layer, would be to move the common functionality into a class that is shared between the two applications and is simply called from the event handler.
Yes, you will have to define event handlers in both apps, but that is a trivial amount of code and also allows you to perform platform-specific error handling (for example, in the web app, you may want to show the exception through a javascript alert while in the winforms app, you may want to show it through a msgbox).
Upvotes: 4