C#如何实现将系统剪切板中内容自动填充进textbox?

C#如何实现将系统剪切板中内容自动填充进textbox?

如题,textbox怎么自动获取系统剪切板中的内容。

推荐使用NuGet程序包:SharpClipboard,可以监听剪切板的不同类型内容,比如:文本,图片或者其他复杂类型的内容,

先看效果:

img

使用示例如下:

using System;
using System.Windows.Forms;
using WK.Libraries.SharpClipboardNS;

namespace WindowsFormsApp1.Forms.Demo2
{
    public partial class Form5 : Form
    {
        private readonly SharpClipboard _clipboard = new SharpClipboard();
        public Form5()
        {
            InitializeComponent();
        }

        private void Form5_Load(object sender, EventArgs e)
        {
            _clipboard.ClipboardChanged += _clipboard_ClipboardChanged;
        }

        private void _clipboard_ClipboardChanged(object sender, SharpClipboard.ClipboardChangedEventArgs e)
        {
            if (e.ContentType == SharpClipboard.ContentTypes.Text)
            {
                textBox1.Text = _clipboard.ClipboardText;
            }

        }
    }

}

定时器 Textbox 没有自动获取的功能,可以使用定时器检查剪贴板内容然后给textbox赋值

【若能帮到您,望给个采纳该答案,谢谢!】
1、通过点击按钮得方式比较容易实现

img

2、前端代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="test.asp.net.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="获取剪切板内容" Height="29px" OnClick="Button1_Click" />
    </form>
</body>
</html>

3、后端代码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows;

namespace test.asp.net
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread((ThreadStart)(() => {
                IDataObject iData = Clipboard.GetDataObject();
                if (iData.GetDataPresent(DataFormats.Text))
                {
                    TextBox1.Text = (String)iData.GetData(DataFormats.Text);
                }
            }));
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
        }
    }
}