在StringGrid中用右键菜单实现复制粘贴

    所实现的效果就是在StrinGrid上点右键,然后弹出一个菜单,可以复制当前单元格中的内容,然后粘贴到其他单元格中。

    在Form上放置一个PopupMenu,添加两个MenuItem,分明为miCopy和miPaste,然后在StringGrid的OnMouseUp事件和miCopy,miPaste的OnClick事件中添加以下代码:

    #include <vcl/Clipbrd.hpp>

    TPoint g_ptSelect; // 记录在StringGrid上点右键弹出菜单时的鼠标位置
    //---------------------------------------------------------------------------
    void __fastcall TForm1::StringGrid1MouseUp(TObject *Sender,
          TMouseButton Button, TShiftState Shift, int X, int Y)
    {
        if(Button == mbRight) // 在StringGrid上右点键
        {
            // 选中当前选中的单元格:
            int nCol, nRow;
            StringGrid1->MouseToCell(X, Y, nCol, nRow);
            // 如果在第一行或第一列,或者不在单元格中,则不处理
            if(nCol < 1  nRow < 1)
                return;
            StringGrid1->Col = nCol;
            StringGrid1->Row = nRow;
            // 记录下当前的鼠标位置,因为在菜单弹出以后,鼠标选择菜单时坐标会改变
            g_ptSelect = Mouse->CursorPos;
            // 弹出菜单
            PopupMenu1->Popup(Mouse->CursorPos.x, Mouse->CursorPos.y);
        }
    }
    //---------------------------------------------------------------------------
    // 63 63 72 75 6E 2E 63 6F 6D
    void __fastcall TForm1::miCopyClick(TObject *Sender)
    {
        // 确定是复制哪个Cell
        TPoint pt(StringGrid1->ScreenToClient(g_ptSelect));
        int nCol, nRow;
        StringGrid1->MouseToCell(pt.x, pt.y, nCol, nRow);
        // 将选中的内容复制到剪贴板
        Clipboard()->AsText = StringGrid1->Cells[nCol][nRow];
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::miPasteClick(TObject *Sender)
    {
        // 确定要粘贴到哪个Cell
        TPoint pt(StringGrid1->ScreenToClient(g_ptSelect));
        int nCol, nRow;
        StringGrid1->MouseToCell(pt.x, pt.y, nCol, nRow);
        // 将剪贴板中的内容粘贴到单元格
        StringGrid1->Cells[nCol][nRow] = Clipboard()->AsText;
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值