In a new VS 2022 solution, targeting .net 6, I have not been able to access the text in the clipboard.
The solution is an update of an earlier solution built in VS 2017 using .net framework 4.62.
In the past I was able to use the Clipboard Class of the System.Windows.Forms package, and retrieve the text with the following line:
string textFromClipBoard = Clipboard.GetText(TextDataFormat.Text);
That line is not working in the new project. The Microsoft documentation states that System.Windows.Forms is not available in .net 6 (https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms?view=windowsdesktop-6.0&viewFallbackFrom=net-6.0), and they do not provide any guidance or alternative.
FYI, my csprog file has the following 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>
Finally - I have confirmed that the text I am looking for is in the Clipboard - I opened Notepad, and did a paste, and the text was all there.
Appreciate any help...
CodePudding user response:
As mentioned already, this project began as a Unit Test project - and does not have a Main() method. The answers that required a decoration of the Main entry point don't apply.
I solved this with 2 methods. One returns the Clipboard text, but runs inside the other, which runs it inside a Single Thread.
Here are the two methods I used (thanks largely to other posts here):
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();
}
CodePudding user response:
I did this the other day using the AutoItX library, I was already using it for something else and it also happened to have a function to get the clipboard contents
string clipboard_contents;
clipboard_contents = AutoItX.ClipGet()
You can get the AutoItX libary from the nuget package manager