我有一个查看剪贴板的简单脚本。一旦它被更改,它会抛出一个事件,查看包含的文本并使用该文本填充数据网格。
事件工作正常并按预期检索文本,但是当我尝试向datagrid添加行时没有任何反应。有什么建议吗?
public void ClipBoardHasChanged(ClipboardMonitor m, ClipboardChangedEventArgs e)
{
string clipBoardValue = (string)e.ClipboardChangedEventArgsT.GetData(DataFormats.StringFormat, true);
this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[0].Cells[0].Value = clipBoardValue;
}
剪贴板类
namespace MarketMatrixCorrelation
{
[DefaultEvent("ClipboardChanged")]
public class ClipboardMonitor : Control
{
IntPtr nextClipboardViewer;
[DllImport("User32.dll")]
protected static extern int SetClipboardViewer(int hWndNewViewer);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
public ClipboardMonitor()
{
this.BackColor = System.Drawing.Color.Red;
this.Visible = false;
nextClipboardViewer = (IntPtr)SetClipboardViewer((int)this.Handle);
}
/// <summary>
/// Clipboard contents changed.
/// </summary>
public delegate void ClipboardChanged(ClipboardMonitor s, ClipboardChangedEventArgs e);
public event ClipboardChanged ClipboardChangedT = delegate { };
protected override void Dispose(bool disposing)
{
ChangeClipboardChain(this.Handle, nextClipboardViewer);
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
// defined in winuser.h
const int WM_DRAWCLIPBOARD = 0x308;
const int WM_CHANGECBCHAIN = 0x030D;
switch (m.Msg)
{
case WM_DRAWCLIPBOARD:
SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
OnClipboardChanged();
break;
case WM_CHANGECBCHAIN:
if (m.WParam == nextClipboardViewer)
nextClipboardViewer = m.LParam;
else
SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
break;
default:
base.WndProc(ref m);
break;
}
}
//Catch when something is posted on the clipboard
private void OnClipboardChanged()
{
try
{
ClipboardChangedEventArgs iData = new ClipboardChangedEventArgs();
iData.ClipboardChangedEventArgsT = Clipboard.GetDataObject();
if (iData.ClipboardChangedEventArgsT.GetDataPresent(DataFormats.StringFormat))
{
ClipboardChangedT(this, iData);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
public class ClipboardChangedEventArgs : EventArgs
{
private IDataObject DataObject;
public IDataObject ClipboardChangedEventArgsT
{
set
{
DataObject = value;
}
get
{
return this.DataObject;
}
}
}
}
答案 0 :(得分:0)
只需将ClipBoardMonitor
放入Form
并将其粘贴到Form Load Event
private void Form1_Load(object sender, EventArgs e)
{
this.clipboardMonitor1.ClipboardChangedT += (o, ex) =>
{
string clipBoardValue = (string)ex.ClipboardChangedEventArgsT.GetData(DataFormats.StringFormat, true);
object[] row = { clipBoardValue };
this.dataGridView1.Rows.Add(row);
};
}