BOOnZ
BOOnZ

Reputation: 848

detect mouse click in parent form, but outside child form

i am trying to implement a UI whereby the parent form loads a child form through showDialog(). the child form would be closed whenever i click anywhere outside the child form, but inside the parent form. clicking anywhere outside the parent form would only cause a normal "alt-tab" action. how do i do this?

Upvotes: 1

Views: 1795

Answers (2)

Orace
Orace

Reputation: 8359

I needed the same behavior.

When my application starts, an advertising form is shown and has to be closed whenever the user click on the main form.

Based on the WM_SETCURSOR message, here my solution (to put in the main form) :

protected override void WndProc(ref Message m)
{
        var vanishingDialog = ActiveForm as IVanishingDialog;

        //0x0201FFFE is for : 0201 (left button down) and FFFE (HTERROR).
        if ((m.Msg == 0x20) && (m.LParam.ToInt32() == 0x0201FFFE) && (vanishingDialog != null))
        {
            vanishingDialog.Vanish();
        }
        else
        {
            base.WndProc(ref m);
        }
}

And my Advertising dialog (or whatever you want to see disappear on a click to the main form) will implement this interface :

public interface IVanishingDialog
{
    /// <summary>
    /// Closes the dialog box.
    /// </summary>
    void Vanish();
}

Work like a charm on seven (no beep).

I just need to improve it in one way : When the user click on a button in the main form, the advertising form close but the button is not pressed. I have to transform and send a new message.

Upvotes: 0

Dan Bystr&#246;m
Dan Bystr&#246;m

Reputation: 9244

If you don't have any controls in the form (if you're viewing a picture for example). Then you can just capture the mouse:

    protected override void OnLoad( EventArgs e )
    {
        base.OnLoad( e );
        this.Capture = true;
    }

And after that, you just check in OnMouseDown if the click is outside your form.

Othewise, this code could be used:

    protected override void WndProc(ref Message m)
    {
        if ( m.Msg==0x86 && (int)m.WParam==0 )
            if ( this.DialogResult==DialogResult.None )
                this.DialogResult = DialogResult.OK;
        base.WndProc (ref m);
    }

It worked great in Windows XP, but in Windows 7 it sounds a beep too, and I haven't investigated why.

Upvotes: 3

Related Questions