There is a scenario where I need to insert data into a word field with the help of the Windows Clipboard.
Implementation steps:
1. Save the Clipboard data to a variable.
2, using the Clipboard to achieve our business.
3. Store the data in the variable back into the Clipboard.
But the result was surprising, baffled. The data inserted into Word is not what we want to insert, but the data on the previous clipboard. Clearly the second step to the beginning of the Clipboard emptied, how the old data inserted into Word? After my testing, dirty data is inserted as soon as the first step is taken. I checked the Clipboard implementation principle, it is to use a piece of application shared memory, to pass data between the application.
From the results of the first step affected the second step, in order not to affect, I think of using multithreading to solve the problem. This is done by opening a thread to perform the first step, and so on, and then the main thread executes the subsequent steps. In this way, the problem is solved. See Source:
EventWaitHandle backupwait =NewEventWaitHandle (false, Eventresetmode.manualreset); Thread Thread=NewThread (() = { if(Clipboard.getdata (dataformats.text)! =NULL) Clipboardtext=Clipboard.getdata (Dataformats.text). ToString (); if(Clipboard.getdata (dataformats.rtf)! =NULL) Clipboardrtf=Clipboard.getdata (DATAFORMATS.RTF). ToString (); Backupwait.set (); }); Thread. Start (); Backupwait.waitone (); Thread.CurrentThread.SetApartmentState (ApartmentState.STA); Clipboard.clear (); Clipboard.setdata (SYSTEM.WINDOWS.FORMS.DATAFORMATS.RTF,NULL); Clipboard.setdata (System.Windows.Forms.DataFormats.Text,NULL); Clipboard.setdata (SYSTEM.WINDOWS.FORMS.DATAFORMATS.RTF, str_content);
Source code Analysis: I used the EventWaitHandle class, the hierarchy of this class see:
From the graph, EventWaitHandle's parent class is Waithandler, there are two subclasses, one is AutoResetEvent, the other is ManualResetEvent. We use Eventresetmode.manualreset to set the pattern manually, similar to the ManualResetEvent class. There are two states of the EventWaitHandle object: the terminating state and the non-terminating state. In a non-terminating state, a thread calls its WaitOne method to prevent the thread from continuing to execute, that is, in a blocked state. when a thread calls the Set method, the other blocked thread is freed and continues execution, at which point the eventwaithandle is in a signaled state. that's how it works.
EventWaitHandle use of C # multithreading synchronization