修复:VS中的中文拷贝到Word时出现乱码
//每個中文字後會連著一到兩個多餘字元
private void btnFix_Click(object sender, EventArgs e)
{
//取得剪貼簿內容
IDataObject dataObject = Clipboard.GetDataObject();
if (dataObject.GetDataPresent(DataFormats.Rtf))
{
//取出RTF格式
string rtf = dataObject.GetData(DataFormats.Rtf) as string;
//以Regex.Replace去除多餘字元(註: 不管是否有問題,一律強制處理)
string fixedRtf =
Regex.Replace(rtf, @"\\uinput2(?<uc>\\u-?\d*)\s..", (m) =>
{
return m.Groups["uc"].Value + "?";
});
//另建新DataObject物件
DataObject newDataObject = new DataObject();
//RTF格式用修正後的字串,其餘依原值
foreach (String t in dataObject.GetFormats())
newDataObject.SetData(t, t == "Rich Text Format" ? fixedRtf : dataObject.GetData(t));
//將修正後內容寫入剪貼簿
Clipboard.SetDataObject(newDataObject, true);
}
}