WebBrowser control on tab making main window inactive
I've got a Visual Studio 2008 .NET 2.0 WinForms app that contains a WebBrowser control on one of the TabPages of its main TabControl. This WebBrowser is only used to display a PDF file that's distributed with the application, and there are no other co开发者_C百科ntrols on that tab except for that WebBrowser control itself.
The problem: At program startup, the application's main window isn't set active. It has to be clicked or selected by [Alt-Tab] before it becomes active.
I've tracked it down to these two lines, fired from FormMain_Load(). I've formed a fully-qualified path to the PDF file I want to display, and called File.Exists() to make sure it's really there (and it is):
Uri uri1 = new Uri("path\\to\\filename.pdf");
webBrowser1.Url = uri1;
If I comment out the 2nd line above, of course it doesn't load the PDF file into the WebBrowser control, but the program can then start up normally -- its main window is active (title bar gets the "active window" colors) and the text cursor is flashing in the first field on the first tab where I put it with TextBox.Select() in FormMain_Shown().
If I add back in that 2nd line, the PDF file gets loaded correctly -- but at startup, the program's main window is inactive (title bar gets the "inactive window" colors). It's not a focus issue, but may be related to z-order. No other windows are obscuring the main window, as I've just started up the program from its desktop icon, and none of the TaskBar buttons at the bottom of the screen show any window as active. It starts up normally, not minimized or maximized.
BTW this TabPage where the WebBrowser control lives isn't the first tab. I only know it loads the PDF file correctly because these lines don't throw an exception and when I click on that tab, the PDF file displays fine. Also FWIW I've got the latest IE updates and Adobe Reader X version.
I thought this might be something quirky about my development machine (Windows 7 64-bit Ultimate with a few IDE plug-ins) but customers running standard 32-bit XP are reporting it too. Also my XP virtual machines inside 7 and Vista show the same thing. As soon as I disable loading the URL, the program starts up as the active window as expected.
Unfortunately, I never found a (non-workaround) solution to the exact same problem that I had in the past. There is a way to prevent IE7 from stealing focus through ActiveX (so I've read), but I never pursued it.
What I ended up doing was loading the .pdf into the WebBrowser control in the OnSelectedIndexChanged event of the TabControl so that the focus wasn't stolen until the user actually entered the tab where the WebBrowser control existed.
I know this isn't the best, but it's all I have.
These look promising though:
Prevent WebBrowser control from stealing focus?
http://www.pcreview.co.uk/forums/hidden-webbrowser-stealing-focus-t2616720.html
精彩评论