Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

If I host a WebBrowser in my application, and a javascript code in the web page shown on my WebBrowser calls window.close() and I click "Yes" on the prompt, my WebBrowser disappears but my form stays open.

I don't want to disable javascript, and not pressing "Yes" is obviously not the solution. What's the best way to handle this? Is this something I can cancel programmatically even after the user presses "Yes"? And also, are there any other javascript tricks like window.close() that could mess up my application that I should be aware of? (My application uses a WebBrowser to search the web, so every possible javascript code should be considered.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
382 views
Welcome To Ask or Share your Answers For Others

1 Answer

In WPF you can catch WM_CLOSE message by attaching to WebBrowser's message loop.

public MainWindow()
{
    InitializeComponent();
    webBrowser.MessageHook += webBrowser_MessageHook;
}

IntPtr webBrowser_MessageHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    switch(msg)
    {
        case 0x0010:    // WM_CLOSE
            handled = true; // cancel event here
            // do additional stuff here    
            break;
    }
    return IntPtr.Zero;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...