简体   繁体   中英

Event-Handling buttons on WinForm from a DLL

I have written a C# utility class (DLL), which gets called by a windows application. Within the windows application, I have setup a backgrounderWorker to allow for time-consuming code not to hog the windows application. The time-consuming code is in the utility class DLL. Now, I setup two buttons on the windows application a 'submit' button - where the time-consuming code gets called in the utility class and a 'cancel' button.

I would like the 'cancel' button to stop the backgroundWorker code if clicked. Problem is the the 'Cancel' button is in the windows application and the code is in the DLL. So is there a way for me to maybe attach the 'cancel' button's 'onClick' eventHandler to the DLL and then have the DLL periodically check to see if the button was pressed?

BTW, the cancel button does work up until the DLL code gets initiated.

Am I correct in my thoughts or is there a better way? Any help would be appreciated.

Yes, It is possible to register to events between projects. all you have to do is have a reference of the winforms application inside your dll, and have the cancel button public. then you can register to any of it's events inside the dll code. However , I'm not sure that this is the best way to do what you want. I think a better way to do it is have a method called Cancel inside the dll and have the cancel button click event call this function. This way your dll is less dependent on your winforms application.

I actually went back and looked at some documentation I had about events and event handling. I did the following in the DLL:

  1. Made a public class an added an eventHandler, my own custom eventArgs, and a subclass (eventWatcher) to host an event (call it onCancel)
  2. I registered eventWatcher to listen for the OnCancel event in the DLL.
  3. I made the eventWatcher public so it can be consumed in the client app.

In the client app, I did the following:

  1. I modified the cancel button to raise the onCancel event. This allowed me to assign a method in the DLL to handle the graceful exiting of the time-consuming code in the DLL.

It now works as expected!

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