Search code examples
c#vb6com-interop

Unable to raise Com Interop event on button click from a Winforms(form) to VB


I have written a COM Interop visible class library in C#. If i open up the vb6 object browser and look at the members exposed, am seeing an event for each and every single exposed member.

In my interop I have a form with one button, So once the user clicks on the button, the event needs to be invoked but it is not happening even though i have invoked the com visible event on button click. But Alternatively, if i call an public C# function from vb6 and inside the function have invoked the com visibile event, then the event is getting triggered in vb6.0

Below is my C# code

public partial class Form1 : Form, EventsInf
{
    public delegate void GetData_delegate(string serviceid);
    public event GetData_delegate GetData;
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Button click entered");
        GetData?.Invoke("test");
    }
    public void raiseevent()
    {
        MessageBox.Show("Event raised from function");
        GetData?.Invoke("test");
    }
   public void show()
    {
        Form1 f1 = new Form1();
        f1.ShowDialog();
    }

My Interface:

[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[ComVisible(true)]
public interface Interface
{
    void GetData(string serviceid);
}

My EventsInf:

[ComVisible(true)]
public interface EventsInf
{
    void raiseevent();
}

VB6.0 Code:

Private WithEvents test As ClassLibrary5.Form1
Private obj As ClassLibrary5.Class1

Private Sub Form_Load()
Set obj = New ClassLibrary5.Class1
Set test = New ClassLibrary5.Form1
test.raiseevent
Me.Visible = False
obj.Show
End Sub

Private Sub test_GetData(ByVal serviceid As String)

End Sub

Please refer to the screenshot, where i have converted the C# dll to tlb and added it as reference to my vb6 project. Now on executing the vb 6 project, winform's(form window) gets launched. But, the breakpoint is not getting hit after pressing the 'click me' button.

Screenshot of breakpoint in code


Solution

  • Root cause: I have writted 'f1.ShowDialog();' inside my class where f1 is the form object.

    Fix: By rewritting the form code with 'this.Show();' inside a public function resolved this issue.

    C# code:

    private void button1_Click(object sender, EventArgs e)
        {
            GetData?.Invoke("test");
        }    
        public void raiseevent()
        {
            this.Show();
            MessageBox.Show("Event raised from function");
        }
    

    VB6.0

     Private WithEvents test As ClassLibrary5.Form1
     Private Sub Form_Load()
     Set test = New ClassLibrary5.Form1
     test.raiseevent
     Me.Visible = False
     End Sub
    
     Private Sub test_GetData(ByVal serviceid As String)
    
     End Sub