在新的VS 2022解决方案中,针对.net 6,我无法访问剪贴板中的文本。
该解决方案是对VS 2017中使用.net框架4.62构建的早期解决方案的更新。
在过去,我能够使用System.Windows.Forms包的剪贴板类,并使用以下行检索文本:
string textFromClipBoard = Clipboard.GetText(TextDataFormat.Text);
这条线在新项目中行不通。微软文档指出,System.Windows.Forms在.net 6 (https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms?view=windowsdesktop-6.0&viewFallbackFrom=net-6.0)中不可用,它们没有提供任何指导或替代。
FYI,我的csprog文件有以下PropertyGroup:
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<RootNamespace>MyTests</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>WinExe</OutputType>
<UseWindowsForms>true</UseWindowsForms>
<IsPackable>false</IsPackable>
</PropertyGroup>
最后-我已经确认,我正在寻找的文本是在剪贴板-我打开了记事本,并做了一个粘贴,文本都在那里。
感谢你的帮助..。
发布于 2022-08-05 22:57:40
如前所述,该项目开始时是一个单元测试项目,并且没有Main()方法。需要对主入口点进行修饰的答案不适用。
我用两种方法解决了这个问题。一个返回剪贴板文本,但在另一个内部运行,后者在单个线程中运行。
下面是我使用的两种方法(主要感谢这里的其他帖子):
internal static string GetTextFromClipboard()
{
string clipText = "";
RunAsSTAThread(
() =>
{
clipText = Clipboard.GetText();
});
return clipText;
}
internal static void RunAsSTAThread(Action goForIt)
{
AutoResetEvent @event = new AutoResetEvent(false);
Thread thread = new Thread(
() =>
{
goForIt();
@event.Set();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
@event.WaitOne();
}
发布于 2022-08-05 23:22:49
前几天我使用了AutoItX库,我已经用它来做其他事情了,而且它也碰巧有一个函数来获取剪贴板的内容。
string clipboard_contents;
clipboard_contents = AutoItX.ClipGet()
您可以从nuget包管理器获得AutoItX清单。
https://stackoverflow.com/questions/73227944
复制相似问题