首页 > 学院 > 开发设计 > 正文

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

2019-11-17 05:29:24
字体:
来源:转载
供稿:网友
ccrun(老妖)本无心写这篇文章,因为功能及代码比较简单,恐有人不屑。只是在回复csdn一位朋友的帖子,久不写这种代码了,一时认真起来,把注释写了个具体,顺便就贴上来吧,也许对刚入门的朋友有所帮助。
所实现的效果就是在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;
}



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表