前言
关于复制粘贴的功能,好像不用劳师动众的写后端代码,JS就可以,但正如大家所知道的,兼容性问题,当然这么通用的功能怎么可能没有一个通用的方案呢,于是便找到了一款jquery插件 jquery.clip, perfect!但本篇并不是写如何使用jquery.clip,而是通过.net 的Clipboard类来实现。
代码实现
一、创建WebAPI,代码如下
using System.Windows.Forms;
using System.Threading;
namespace JYZS.Api
{
public class ClipboardController : ApiController
{
[HttpGet]
public string CopyToClipboard(string content)
{
Thread newThread = new Thread(new ThreadStart(() => { _CopyToClipboard(content); }));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
//newThread.Join();//阻塞调用线程,直到被调用线程结束
return "";
}
private void _CopyToClipboard(string content)
{
System.Windows.Forms.Clipboard.SetText(content);
}
[HttpGet]
public string PasteFromClipboard()
{
string text = "";
try
{
Thread newThread = new Thread(new ThreadStart(() => { text = _PasteFromClipboard(); }));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Priority = ThreadPriority.Highest;
newThread.Start();
newThread.Join();//阻塞调用线程,直到被调用线程结束
return text;
}
catch
{
return "";
}
}
private string _PasteFromClipboard()
{
return System.Windows.Forms.Clipboard.GetText();
}
}
}
二、前端调用
function fn_CopyToClipboard() {
$.ajax({
type: 'GET',
url: '/api/Clipboard/CopyToClipboard',
data: { content: $.trim($('#Content').val()) },
success: function (msg) {
if (msg == null || msg == '') { alert('已复制到剪切板'); }
else alert(msg);
},
error: function (err) {
alert('复制到剪切板失败');
}
});
}
function fn_PasteFromClipboard() {
$.ajax({
type: 'GET',
url: '/api/Clipboard/PasteFromClipboard',
data: { },
success: function (msg) {
if (msg == null || msg == '') { alert('获取剪切板数据失败'); }
else alert(msg);
},
error: function (err) {
alert('获取剪切板数据失败');
}
});
}
POST:hope helpful to you!!!
类名、方法名及命名空间均为本人项目中命名,使用时请注意修改~