ccrun(老妖)本无心写这篇文章,因为功能及代码比较简单,恐有人不屑。只是在回复csdn一位朋友的帖子,久不写这种代码了,一时认真起来,把注释写了个详细,顺便就贴上来吧,也许对刚入门的朋友有所帮助。
所实现的效果就是在StrinGrid上点右键,然后弹出一个菜单,可以复制当前单元格中的内容,然后粘贴到其他单元格中。
在Form上放置一个PopupMenu,添加两个MenuItem,分明为miCopy和miPaste,然后在StringGrid的OnMouseUp事件和miCopy,miPaste的OnClick事件中添加以下代码:
#include <vcl\Clipbrd.hpp>
TPoint g_ptSelect;
void __fastcall TForm1::StringGrid1MouseUp(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
if(Button == mbRight)
{
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);
}
}
void __fastcall TForm1::miCopyClick(TObject *Sender)
{
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)
{
TPoint pt(StringGrid1->ScreenToClient(g_ptSelect));
int nCol, nRow;
StringGrid1->MouseToCell(pt.x, pt.y, nCol, nRow);
StringGrid1->Cells[nCol][nRow] = Clipboard()->AsText;
}