剪貼板程式設計教學多聚焦文字處理,檔案操作(剪切/複製/貼上)鮮見系統性講解。本文分享 CodeProject 發現的實作方案,並提出一個困擾許久的行動裝置跨平台貼上難題,期待社群共同破解。
void CopyToClipboard(bool cut)
{
string[] files = GetSelection(); // 取得選取檔案路徑陣列
if (files != null)
{
// 關鍵:必須用陣列形式,單一檔案也要包成陣列
IDataObject data = new DataObject(DataFormats.FileDrop, files);
// 設定「預期放置效果」:2=Move(剪切), 5=Copy(複製)
MemoryStream memo = new MemoryStream(4);
byte[] bytes = new byte[] { (byte)(cut ? 2 : 5), 0, 0, 0 };
memo.Write(bytes, 0, bytes.Length);
data.SetData("Preferred DropEffect", memo);
Clipboard.SetDataObject(data);
}
}
private void pasteMenuItem_Click(object sender, EventArgs e)
{
IDataObject data = Clipboard.GetDataObject();
if (!data.GetDataPresent(DataFormats.FileDrop)) return;
string[] files = (string[])data.GetData(DataFormats.FileDrop);
// 讀取操作旗標
MemoryStream stream = (MemoryStream)data.GetData("Preferred DropEffect", true);
int flag = stream.ReadByte();
if (flag != 2 && flag != 5) return; // 非標準旗標,放棄
bool cut = (flag == 2); // 2=Move, 5=Copy
foreach (string file in files)
{
string dest = homeFolder + "\\" + Path.GetFileName(file);
try
{
if (cut)
File.Move(file, dest); // 剪切:移動
else
File.Copy(file, dest, false); // 複製:不覆蓋
}
catch (IOException ex)
{
MessageBox.Show(this, "操作失敗:\n\n" + ex.Message, "檔案操作失敗",
MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
RefreshView();
}
DataFormats.FileDrop 格式要求 string[],單檔案也要 new string[] { path }。0x02 (2) = Move(剪切)0x05 (5) = Copy(複製)DROPEFFECT 定義(DROPEFFECT_MOVE=2, DROPEFFECT_COPY=5)。行動裝置檔案路徑通常為 UNC 風格或裝置專屬路徑(如 \\Application Data\...、\Storage Card\...),PC 端無法直接解析存取。即使剪貼板能傳遞路徑,PC 也無法對該路徑執行 File.Copy/Move。
如何讓 PC 端應用程式:
呼籲社群高手:若有經驗處理跨裝置剪貼板檔案傳輸(特別是 Windows Mobile/CE 到 Desktop),請不吝分享關鍵 API、資料格式或架構設計。這對構建無縫跨平台檔案交互體驗至關重要。