Haggisatonal
Haggisatonal

Reputation: 256

Prevent focus change in a form when the form activates by click

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

Answers (2)

Reza Aghaei
Reza Aghaei

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

Aleksa Ristic
Aleksa Ristic

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

Related Questions