简体   繁体   中英

Adding events in VB.Net

I have wrtitten the code below in C#, but I would need to re-write it in VB.Net. How can I do it?

       public void ImprimirDXReport(DXReportParams reportParams, int trayIdx, bool preview = false)
    {
        ...

        report.PrintingSystem.StartPrint += PrintingSystem_StartPrint;

        ...
    }

    private void PrintingSystem_StartPrint(object sender, PrintDocumentEventArgs e)
    {
        e.PrintDocument.DefaultPageSettings.PaperSource = e.PrintDocument.PrinterSettings.PaperSources[this.TrayIndex];
    }

I've been reading about RaiseEvent and AddHandler , but I'm pretty confused about them.

Thank you.

First, for code converting I recommend:
https://converter.telerik.com/

That's not that difficult. The class which will fire the events should be declared like this:

Public Class A

    Public Event SomethingDone(sender As Object, e As EventArgs)

    Public Sub DoSomething()
        RaiseEvent SomethingDone(Me, New EventArgs)
    End Sub

End Class

So this class has a declared event SomethingDone and this will be fired when the method raises it.

The recieving class could be declared like this:

Public Class B

    Private WithEvents DoIt As A

    Private Sub DoIt_SomethingDone(sender As Object, e As EventArgs) Handles DoIt.SomethingDone
        Dim X As Integer
        ' Some other stuff
    End Sub

End Class

So this class uses the class A and can recieve their events. The keyword is here "WithEvents". You have to declare the class with this keyword to recieve their events.

In the IDE you have now the possibility to choose the class and choose an event like you do with control events.

The event handler will be automatically created with the keyword "Handles" at the end. This indicates which event(s) will be handled.

If you want to give parameters with the event, you have to create a new class which inherits from EventArgs.

Your code would be sufficent maybe with:

Private Sub PrintingSystem_StartPrint(ByVal sender As Object, ByVal e As PrintDocumentEventArgs) Handles report.PrintingSystem.StartPrint
    e.PrintDocument.DefaultPageSettings.PaperSource = e.PrintDocument.PrinterSettings.PaperSources(Me.TrayIndex)
End Sub

For the AddHandler, AddressOf stuff I recommend
https://www.codeproject.com/Articles/5041/Step-by-Step-Event-handling-in-VB-NET

I dont want to go in to Delegates, that's to much stuff for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM