In a project, it is necessary to read the CF card RFID by means of COM port.
problem : When I close the module, and then the second time to hit the module, the following error "access to port Com1 denied" (programming this industry, is not found object, is XXX refused!) ):
Breakpoint Debugging: An exception occurred when the user control loaded event attempted to open a COM port: Access to Port Com1 was denied.
Finally find the reason and solution:
The COM port is opened when the user control is loaded, and the COM port is closed when the module is closed, but the user control does not have a closing or closed event. So I used the unloaded event to solve this problem, repeatedly open the shutdown module, no longer "access to COM port denied" error:
Unloaded event:
To turn off COM ports:
Summary: WPF window.closing, window.closed, frameworkelement.unloaded
The difference between the three:
window.closing Event: Occurs immediately after close is called, and can be processed to cancel closing the window.
You can handle Closing to detect when a window is closed (for example, when Close is called). In addition, you can use Closing to prevent the window from closing. To prevent the window from closing, you can set the Cancel property of the CancelEventArgs parameter to true.
The Closing event is raised when Close is called and the window's Close button is clicked.
code example:
Private voidWindow_closing (Objectsender, CancelEventArgs e) { if( This. IsLoaded) {Messageboxresult result= MessageBox.Show ("do you want to exit the program? ","Tips", Messageboxbutton.yesno, messageboximage.question); if(Result = =messageboxresult.yes) {//Do something to record the shutdown eventDateTime Shutdowndt=DateTime.Now; } Else{E.cancel=true; } } }
View Code
window.closed Event: Occurs when the window is about to close.
Once this event is raised, the window cannot be prevented from closing.
frameworkelement.unloaded Event: Occurs when an element is removed from the element tree of the loaded element.
In some cases it will not be triggered. For example, when window is closing, it is not going to trigger the unloaded event of its child element.
Loaded and unloaded are related to the UI. Closing is related to the form book.
For example, when the window is initialized, the loaded is not triggered if the window is hidden.
Because it only fires when the control starts to be visible. Similarly, unloaded is.
Access to Port Com1 is denied