Problem with clipboard class
I have created a application which checks if the text in clipboard starts with "file", and if it starts with the word file it process the clipboard text and then replaces it with < a href="some value">
For example it the clipboard string is
file:///C:/Users/Searock/Desktop/dotnet/Apress.Pro.VB.2008.and.the.dot.NET.3.5.Platform.3rd.Edition.Mar.2008.html#link22
then the program will process the clipboard txt and then replace it with < a href="#link22">
Here's my code :
Variable Declaration :
Dim strProcess As String
Dim intPos As Integer
Dim check As String
Dim strBuilder As New StringBuilder()
Form Load :
bwCopyPaste.RunWorkerAsync()
BackGroundWorker DoWork event :
While (True)
Thread.Sleep(150)
If bwCopyPaste.CancellationPending = True Then
Exit While
End If
check = Clipboard.GetText()
If check <> "" Then
If check.StartsWith("file") Then
Try
strProcess = Clipboard.GetText()
intPos = strProcess.LastIndexOf("#")
strProcess = strProcess.Substring(intPos, strProcess.Length - intPos)
strBuilder.AppendFormat("<a href=""{0}"">", strProcess)
Clipboard.SetText(strBuilder.ToString())
Catch ex As Exception
MessageBox.Show("Invalid Url", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error)
Application.Restart()
Finall开发者_StackOverflowy
strBuilder.Clear()
End Try
End If
End If
End While
I don't get any runtime errors, but even if there is any text in the clipboard, this statement
check = Clipboard.GetText()
If check <> "" Then
always returns me a false value.
Can anyone point me to a right direction ?
Thanks.
The problem here is that BackgroundWorkers are MTA (Multi Thread Apartments) and the Clipboard class can only be used by STA (Single Thread Apartments) threads.
Try something like this in your load where "bwCopyPaste.RunWorkerAsync()" resides.
If Clipboard.ContainsText() then
bwCopyPaste.RunWorkerAsync(ClipBoard.GetText())
End if
Then you can get at the value passed into the background worker through it's eventArgument.
精彩评论