剪贴板类的问题 [英] Problem with clipboard class
问题描述
我创建了一个应用程序,它检查剪贴板中的文本是否以file"开头,如果它以 word file 开头,它会处理剪贴板文本,然后将其替换为 <a href="some value">
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">
例如剪贴板字符串是
file:///C:/Users/Searock/Desktop/dotnet/Apress.Pro.VB.2008.and.the.dot.NET.3.5.Platform.3rd.Edition.Mar.2008.html#link22
file:///C:/Users/Searock/Desktop/dotnet/Apress.Pro.VB.2008.and.the.dot.NET.3.5.Platform.3rd.Edition.Mar.2008.html#link22
然后程序将处理剪贴板txt,然后将其替换为<a href="#link22">
then the program will process the clipboard txt and then replace it with < a href="#link22">
这是我的代码:
变量声明:
Dim strProcess As String
Dim intPos As Integer
Dim check As String
Dim strBuilder As New StringBuilder()
表单加载:
bwCopyPaste.RunWorkerAsync()
BackGroundWorker DoWork 事件:
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()
Finally
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
总是返回一个错误值.
谁能指出我正确的方向?
Can anyone point me to a right direction ?
谢谢.
推荐答案
这里的问题是 BackgroundWorkers 是 MTA(多线程单元)并且剪贴板类只能由 STA(单线程单元)线程使用.
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.
在bwCopyPaste.RunWorkerAsync()"所在的负载中尝试类似的操作.
Try something like this in your load where "bwCopyPaste.RunWorkerAsync()" resides.
If Clipboard.ContainsText() then
bwCopyPaste.RunWorkerAsync(ClipBoard.GetText())
End if
然后您可以通过它的 eventArgument 获取传递给后台工作程序的值.
Then you can get at the value passed into the background worker through it's eventArgument.
这篇关于剪贴板类的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!