Search code examples
c#viewrangeoffice-interop

Selecting a Word Interop Header Range causes Word to switch to Draft View


When selecting a Header Range using .Select(), Microsoft Word automatically switches to Draft View from my current view type (Print layout). How do I stop Word from switching to Draft View?

The following code example demonstrates what I'm doing:

 // this.Document is a Microsoft.Office.Interop.Word.Document
 Section section = this.Document.Sections.First;
 foreach (HeaderFooter header in section.Headers)
 {
   if (header.Exists) 
   {
     header.Range.Select(); // When I call this, Word switches to Draft View.
     break;
   }
 }

Edit (3):

Apparently saving the View Type and resetting it does work. However, this causes a annoying flickering when Word switches to Draft View and then back to Print Layout. Additionally, when I double click in the main document space to get out of the header section, Word switches back to Draft View.

 WdViewType viewType = this.Document.ActiveWindow.View.Type;
 range.Select();
 this.Document.ActiveWindow.View.Type = viewType;

Solution

  • The View.SeekView property must be set for all view types excluding wdNormalView (Draft View) before the range is selected.

    var window = this.Document.ActiveWindow;
    // wdNormalView == Draft View, where SeekView can't be used and isn't needed.
    if (window.View.Type != WdViewType.wdNormalView)
    {
      // -1 Not Header/Footer, 0 Even page header, 1 Odd page header, 4 First page header
      // 2 Even page footer, 3 Odd page footer, 5 First page footer
      int rangeType = range.Information[WdInformation.wdHeaderFooterType];
      if (rangeType == 0 || rangeType == 1 || rangeType == 4)
        window.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
      if (rangeType == 2 || rangeType == 3 || rangeType == 5)
        window.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;
    }
    header.Range.Select();