分类: C/C++
2008-08-04 09:32:15
ContextMenu myContextMenu = ... myControl.ContextMenu = myContextMenu;就这么简单。只要按照上述方法设置好属性,当用户单击右键时,菜单便会自动显示出来。此外,如果你想进一步实现右键拖拽,这才涉及到事件处理。在 MFC 中,你会自然而然想到用OnRButtonDown 和 OnRButtonUp 实现,但是那不是 Windows 窗体(Forms)的工作方式。虽然许多窗口类确实提供了可以改写的虚拟函数来处理常用消息(如:Form.OnActivated 和 Form.OnClosed),但是在.NET框架中编程,你必须要学会用事件来思考,而且要了解一个类提供了哪些事件。下面这个表列出了被 Control 类提供的比较常用的事件:
Click | HelpRequested | MouseLeave |
ContextMenuChanged | Invalidated | MouseMove |
DoubleClick | KeyDown | MouseUp |
DragDrop | KeyPress | MouseWheel |
DragEnter | KeyUp | Move |
DragLeave | Layout | Paint |
DragOver | Leave | ParentChanged |
EnabledChanged | LostFocus | Resize |
Enter | MouseDown | SizeChanged |
FontChanged | MouseEnter | StyleChanged |
GotFocus | MouseHover | TextChanged |
public class MyControl : Control { // 构造函数 public MyControl() { // 安装右键按下事件处理器 this.myctl1.MouseDown = new MouseEventHandler(this.OnMouseDown); } // 处理例程 private void OnMouseDown(object sender, MouseEventArgs e) { if (e==MouseButtons.Right) // do something } }表一里有三个有用的鼠标事件是在 MFC 中不能直接处理的:MouseEnter、 MouseHover 和 MouseLeave。在 Win32 里,要处理这些事件必须通过专门的 TrackMouseEvent 函数。.NET 框架
控制或控件 | 鼠标左键单击 | 鼠标左键双击 | 鼠标右键单击 | 鼠标右键双击 | 鼠标中键单击 | 鼠标中键双击 |
---|---|---|---|---|---|---|
MonthCalendar, DateTimePicker, RichTextBox, HScrollBar, VScrollBar | None | None | None | None | None | None |
Button, CheckBox, RadioButton | Click | Click, Click | None | None | None | None |
ListBox, CheckedListBox, ComboBox | Click | Click, DoubleClick | None | None | None | None |
TextBox, DomainUpDown, NumericUpDown | Click | Click, DoubleClick | None | None | None | None |
*TreeView, *ListView | Click | Click, DoubleClick | Click | Click, DoubleClick | None | None |
ProgressBar TrackBar | Click | Click, Click | Click | Click, Click | Click | Click, Click |
Form, DataGrid, Label, LinkLabel, Panel,GroupBox, PictureBox, Splitter, DoubleClick, StatusBar,ToolBar, TabPage, **TabControl | Click | Click, DoubleClick | Click | Click, DoubleClick | Click | Click, DoubleClick |
* 鼠标指针必须在子对象上方
(TreeNode 或 ListViewItem) ** TabControl 必须在其 TabPages 页集合中至少有一个 TabPage。 |
protected override void WndProc(ref Message m) { // 值来自 winuser.h const int WM_NCLBUTTONDOWN = 0x00A1; if (m.Msg == WM_NCLBUTTONDOWN) { //do something } base.WndProc(ref m); // 这一步不能忘! }我写了一个例子程序 MouseTrap,如图一所示,