在 TStringGrid 上右鍵彈出選單,複製當前儲存格文字到剪貼簿,或從剪貼簿貼上到目標儲存格。
OnMouseUp 觸發時取得的 X, Y 是相對 StringGrid 用戶區的座標。但彈出選單後使用者移動滑鼠點選選單項目,Mouse->CursorPos 已改變。必須在 OnMouseUp 即刻保存螢幕座標,供後續選單事件使用。
#include
TPoint g_ptSelect; // 全域/表單成員:保存右鍵彈出時的螢幕座標
//---------------------------------------------------------------------------
void __fastcall TForm1::StringGrid1MouseUp(TObject* Sender,
TMouseButton Button, TShiftState Shift, int X, int Y) {
if (Button != mbRight) return;
int Col, Row;
StringGrid1->MouseToCell(X, Y, Col, Row);
if (Col < 1 || Row < 1) return; // 忽略標題列/欄
StringGrid1->Col = Col;
StringGrid1->Row = Row;
g_ptSelect = Mouse->CursorPos; // 關鍵:保存螢幕座標
PopupMenu1->Popup(Mouse->CursorPos.x, Mouse->CursorPos.y);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::miCopyClick(TObject* Sender) {
// 由保存的螢幕座標反推儲存格
TPoint pt = StringGrid1->ScreenToClient(g_ptSelect);
int Col, Row;
StringGrid1->MouseToCell(pt.x, pt.y, Col, Row);
Clipboard()->AsText = StringGrid1->Cells[Col][Row];
}
//---------------------------------------------------------------------------
void __fastcall TForm1::miPasteClick(TObject* Sender) {
TPoint pt = StringGrid1->ScreenToClient(g_ptSelect);
int Col, Row;
StringGrid1->MouseToCell(pt.x, pt.y, Col, Row);
StringGrid1->Cells[Col][Row] = Clipboard()->AsText;
}
| 方法 | 用途 |
|---|---|
MouseToCell(X, Y, Col, Row) | 用戶區座標 → 儲存格索引 |
ScreenToClient(Point) | 螢幕座標 → 控制項用戶區座標 |
Mouse->CursorPos | 取得當前滑鼠螢幕座標 |
Clipboard()->AsText | 剪貼簿純文字讀寫 |
Clipbrd.hpp:連結錯誤 [Linker Error] Unresolved external 'Clipboard()'Ctrl+C/V/X:在 OnKeyDown 處理