龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

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

时间:2009-12-22 15:42来源:未知 作者:admin 点击:
分享到:
ccrun(老妖)本无心写这篇文章,因为功能及代码比较简单,恐有人不屑。只是在回复csdn一位朋友的帖子,久不写这种代码了,一时认真起来,把注释写了个具体,顺便就贴上来吧,也许

ccrun(老妖)本无心写这篇文章,因为功能及代码比较简单,恐有人不屑。只是在回复csdn一位朋友的帖子,久不写这种代码了,一时认真起来,把注释写了个具体,顺便就贴上来吧,也许对刚入门的朋友有所帮助。

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

  

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

  

  #include

  

  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;

  }

  

  

  

精彩图集

赞助商链接