首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

StringGrid 右鍵選單複製貼上:PopupMenu + Clipboard + MouseToCell 座標轉換

     編輯:VC 教學

元件配置

  • `TStringGrid` (名 `StringGrid1`)
  • `TPopupMenu` (名 `PopupMenu1`) → 兩項目:`miCopy` (複製)、`miPaste` (貼上)
  • 全域 `TPoint g_ptSelect` 記錄右鍵彈出時滑鼠螢幕座標。

事件代碼


// StringGrid1 OnMouseUp
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(g_ptSelect.x, g_ptSelect.y);
}

// miCopy OnClick
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];
}

// miPaste OnClick
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` 將客戶區/螢幕座標轉為儲存格索引。
  • 右鍵彈出選單時滑鼠移動,座標會變,**必須在 `OnMouseUp` 即刻記錄 `CursorPos`**,選單項目再轉回客戶區查詢。
  • 需 `#include ` 使用 `Clipboard()`。

擴充:多儲存格選取

若 `Options` 含 `goRangeSelect`,可用 `Selection` 屬性 (TRect) 取得範圍,迴圈複製/貼上多儲存格。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved