I'm trying to programatically set IE options such that when I print a page from my control, it will not print the header and footer, as is the default setting for printing a web page from IE. I found out how to do so from http://support.microsoft.com/kb/313723, however I am having problems setting it back as desired.

What I want to do is have the values in the registry clear when I click the print button (which will bring up the print dialog using webbrowser.ShowPrintDialog() ), and then set it back right away. When I use the following code, though, it all happens so fast that when the user goes to print, the header and footer have been replaced again.

private void print(bool preview)
        {
            string strKey = "Software\\Microsoft\\Internet Explorer\\PageSetup";
            bool bolWritable = true;
            string strName1 = "footer";
            string strName2 = "header";
            object oldFooter = "";
            object oldHeader = "";

            RegistryKey oKey = Registry.CurrentUser.OpenSubKey(strKey, bolWritable);

            try
            {
                oldFooter = oKey.GetValue(strName1);
                oldHeader = oKey.GetValue(strName2);
            }
            catch { }

            oKey.SetValue(strName1, "");
            oKey.SetValue(strName2, "");
            //oKey.Close();

            if (preview == true)
                this.webBrowser1.ShowPrintPreviewDialog();
            else
                this.webBrowser1.Print();

            oKey.SetValue(strName1, oldFooter);
            oKey.SetValue(strName2, oldHeader);
            oKey.Close();

        }

Can anybody think of a creative way for me to delete the registry key and re-create it at the right time? I don't want to do it at program open/close, because I can't guarantee that the program will not crash, and then cause the setting to not be re-applied. And I don't want to rely on Print(), because that may not always print to the user's default (or even desired) printer. I want them to be able to choose their printer.

You can split the program into two functions --
When it is run once, it sets the values
When it is run again, it unsets the values.

Sadly that solution is worse than anything else I could have thought, but thanks for the input.

I ended up solving it after hours of thinking and tweaking. I had it delete the values when pushing the print button, and re-setting the values using the Activated() event. This way, the values do not get reset before the print dialog box closes. I also put the code in the Closing() event for good measure, just to make sure that when the app closes, that the values are put back if they hadn't already.a

This question has already been answered. Start a new discussion instead.