답변:
다른 어셈블리와 다른 네임 스페이스에있는 두 개의 클래스가 있습니다.
WinForms : 다음 네임 스페이스 선언을 사용 Main하고 [STAThread]속성 으로 표시되어 있는지 확인하십시오 .
using System.Windows.Forms;WPF : 다음 네임 스페이스 선언 사용
using System.Windows;콘솔 :에 참조를 추가하고 System.Windows.Forms다음 네임 스페이스 선언을 사용 Main하고 [STAThread]속성 으로 표시되어 있는지 확인하십시오 . 다른 답변의 단계별 가이드
using System.Windows.Forms;정확한 문자열을 복사하려면 (이 경우 리터럴) :
Clipboard.SetText("Hello, clipboard");
텍스트 상자의 내용을 복사하려면 TextBox.Copy ()를 사용 하거나 먼저 텍스트를 가져온 다음 클립 보드 값을 설정하십시오.
Clipboard.SetText(txtClipboard.Text);
예를 보려면 여기를 참조하십시오 . 또는 ... 공식 MSDN 문서 또는 여기 WPF .
비고 :
클립 보드는 데스크톱 UI 개념으로 ASP.Net과 같은 서버 측 코드에서 설정하려고하면 서버의 값만 설정하며 사용자가 브라우저에서 볼 수있는 내용에는 영향을 미치지 않습니다. 링크 된 답변을 사용하면 클립 보드 액세스 코드 서버 측을 실행할 수 있지만 SetApartmentState달성하려는 것은 아닙니다.
이 질문 코드에서 다음 정보를 계속 사용한 후에도 여전히 예외가 발생하면 "현재 스레드를 STA (단일 스레드 아파트)로 설정해야합니다."오류를 클립 보드에 문자열 복사
이 질문 / 답변은 일반 .NET에 적용됩니다. .NET Core 용 -.Net Core-클립 보드에 복사?
들어 콘솔 단계별 방식으로 프로젝트를 먼저 추가해야 System.Windows.Forms참조. 다음 단계는 Visual Studio Community 2013 with .NET 4.5에서 작동합니다.
System.Windows.Forms.그런 다음 using코드 맨 위에 다른 명령문과 함께 다음 명령문을 추가하십시오 .
using System.Windows.Forms;
그런 다음 다음 중 하나를 추가하십시오 Clipboard. SetText코드에 대한 진술 :
Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
마지막 으로 다음과 같이 메소드에 추가 STAThreadAttribute하여 :MainSystem.Threading.ThreadStateException
[STAThreadAttribute]
static void Main(string[] args)
{
// ...
}
StackOverflowException즉시 선행 STAThreadAttribute는 .NET Framework 시스템 클래스 라이브러리는 =)
클립 보드에 WPF C # 대처를 사용 하여이 문제에 대한 나의 경험 System.Threading.ThreadStateException은 모든 브라우저에서 올바르게 작동하는 코드와 함께 있습니다.
Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();
이 게시물에 대한 크레딧 여기
그러나 이것은 localhost에서만 작동하므로 서버에서는 작동하지 않으므로 시도하지 마십시오.
서버 측에서는을 사용하여 수행했습니다 zeroclipboard. 많은 연구 끝에 유일한 방법.
Clip.exe는 Windows에서 클립 보드를 설정하기위한 실행 파일입니다. 참고 이 작동하지 않는 다른 운영 체제 여전히 짜증 윈도우 이외.
/// <summary>
/// Sets clipboard to value.
/// </summary>
/// <param name="value">String to set the clipboard to.</param>
public static void SetClipboard(string value)
{
if (value == null)
throw new ArgumentNullException("Attempt to set clipboard with null");
Process clipboardExecutable = new Process();
clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
{
RedirectStandardInput = true,
FileName = @"clip",
};
clipboardExecutable.Start();
clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
// When we are done writing all the string, close it so clip doesn't wait and get stuck
clipboardExecutable.StandardInput.Close();
return;
}