C# MonthCalendar control Get date under cursor
-
20-02-2021 - |
문제
Is there a way to get the date under the cursor on the MonthCalendar control? I'd like to collect this on right click to pass into a dialog. Right clicking doesn't seem to trigger it's click event. I tried overloading the MouseDown event, but that didn't seem to help either.
해결책
Yes, MonthCalendar has its own context menu so the right-button click event is disabled. Surgery is required to re-enable it. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.
using System;
using System.Drawing;
using System.Windows.Forms;
class MyCalendar : MonthCalendar {
public event MouseEventHandler RightClick;
protected override void WndProc(ref Message m) {
if (m.Msg == 0x205) { // Trap WM_RBUTTONUP
var handler = RightClick;
if (handler != null) {
var pos = new Point(m.LParam.ToInt32());
var me = new MouseEventArgs((MouseButtons)m.WParam.ToInt32(), 1, pos.x, pos.y, 0);
handler(this, me);
}
this.Capture = false;
return;
}
base.WndProc(ref m);
}
}
You now have a RightClick event that you can subscribe. Something similar to this:
private void myCalendar1_RightClick(object sender, MouseEventArgs e) {
var hit = myCalendar1.HitTest(e.Location);
if (hit.HitArea == MonthCalendar.HitArea.Date) {
var dt = hit.Time;
MessageBox.Show(dt.ToString()); // Display your context menu here
}
}
다른 팁
if you want capture right click, please try this
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
}
}
more info can be found here
http://msdn.microsoft.com/en-us/library/system.windows.forms.mouseeventargs.aspx