简体   繁体   中英

Calling a C# asynchronus method from a VB6 application

I have a C# dll that when the main method is called, it opens a windows form. This dll is currently accessed through VBA by a vendor application. The problem is that when the dll is called and the form opens, the user loses the ability to interact with the vendor application. I was hoping that if I could modify the dll to support an asynchronus call, then the control could be returned to the calling application to allow the user to turn pages, zoom in or out, etc. Then once the user completes the pop-up form we could have a callback or something to return the information to the vba app customizations.

Rather than making the async call from VB, it would be far easier to modify the C# code to open the window asynchronously, and then return.

You could do this just by changing the line that opens the window from .ShowDialog() to .Show() .

Obviously, this may not be an option if you don't have access to the C# dll's code, but I thought I would suggest it.


If you do decide to change to use Show() instead of ShowDialog() you may have to handle your dialog result differently.

You're new code will look something like this:

MyForm win = new MyForm();
win.Show();

A non modal dialog doesn't block the calling code, so your calling code will continue without waiting for a result.

The simplest way to handle this would be to attach an event handler to the form's .OnClosed event . This will then be triggered when the user closes the form.

MyForm win = new MyForm();
win.OnClosed += new EventHandler<FormClosedEventArgs>(YourEventHandlerMethod)
win.Show();

You can add a public boolean property to the form (with a private setter) that you set internally when the ok/cancel buttons are pressed (Along with calling the close method). You can then check this property after the form has closed from within your on closed handler. (The sender property will be your reference to the form, you'll just have to cast it to the correct type first).

So your event handler method will look like this:

private void EventHandler<FormClosedEventArgs> YourEventHandlerMethod(Object sender, FormClosedEventArgs e)
{
    MyForm f = (MyForm)sender;
    bool result = f.TheResultProperty;

    // Now do your callback.
}

Finally, now you have some code that runs after the form closes, and has access to the forms result, you just need to let your VBA code know it's ready - I'll leave this up to you.

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