Reputation: 256
Is it possible in a C# WinForms app to click anywhere on an unfocused form (to focus the form), without also focusing / selecting any controls at the click point?
I'm trying to mimic the way Excel works where if you click on an unfocused Excel workbook / sheet, it will focus (and bring to front) the workbook / sheet BUT will not change the selected cell.
Upvotes: 1
Views: 985
Reputation: 125277
You can override WndProc
and handle WM_MOUSEACTIVATE
, then check if the current form is not active form, set MA_ACTIVATEANDEAT
as result to activate the window, and discard the mouse message.
const int WM_MOUSEACTIVATE = 0x0021;
const int MA_ACTIVATEANDEAT = 2;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_MOUSEACTIVATE && Form.ActiveForm != this)
m.Result = (IntPtr)MA_ACTIVATEANDEAT;
else
base.WndProc(ref m);
}
Using above code, when you click on another form or one of its controls, the other form activates, but the clicked control doesn't receive mouse click and the the active control on the other form will not change.
Upvotes: 3
Reputation: 2499
Well it is uses 2 handlers, Form deactivated and Form Activated:
private void Form_Activated(object sender, EventArgs e)
{
dataGridView1.Enabled = true;
}
private void Form_Deactivate(object sender, EventArgs e)
{
dataGridView1.Enabled = false;
}
Also could be used DataGridView's
focus handlers if you want inform control like this.
Upvotes: 0