How to: Write Conditional Logic That Determines the Run-time Environment

The Environment property of the Application class gets a reference to an Environment object, which can be used to determine which runtime environment (InfoPath, Web browser, or mobile browser) was used to open the form.

Example

Determining Which Runtime Environment a Form is Running In

The Environment class provides the IsBrowser and IsMobile properties which enable you to determine what editing environment was used to open a form template. If both properties return false, the form template was opened in Microsoft Office InfoPath 2007. If either property returns true, the form template was opened from Microsoft Office Forms Server 2007 or from an appropriately configured document library on Microsoft Office SharePoint Server 2007 running InfoPath Forms Services in the program for the corresponding property: a Web browser (IsBrowser property) or a mobile browser (IsMobile property).

In the following example, if the form is opened in a browser or mobile browser, the value of field1 (which is bound to a Text Box control) is set to a string to indicate which runtime environment the form was opened in. If the form is opened in InfoPath, the System.Windows.Forms.MessageBox.Show method (which isn't available when a form is running in a browser) is used to display a message box.

Important

When you create the form template for the following code sample, select the Enable browser-compatible features only check box on the Design a Form Template dialog box. (Alternatively, you can select the Design a form template that can be opened in a browser or InfoPath check box under the Compatibility category of the Form Options dialog box.) To support the MessageBox class, add a reference to System.Windows.Forms on the .NET tab of the Add Reference dialog box in Microsoft Visual Studio Tools for Applications (VSTA) or Visual Studio, and then add a using or Imports directive for System.Windows.Forms in the declarations section of the form code module.

if(this.Application.Environment.IsBrowser)
{
   CreateNavigator().SelectSingleNode(
      "/my:myFields/my:field1", NamespaceManager).
      SetValue("Running in a browser.");
}
else if (this.Application.Environment.IsMobile)
{
   CreateNavigator().SelectSingleNode(
      "/my:myFields/my:field1", NamespaceManager).
      SetValue("Running in a mobile browser.");
}
else
{
   MessageBox.Show("This form is running in InfoPath.");
}
If (Me.Application.Environment.IsBrowser) Then
   CreateNavigator().SelectSingleNode(_
      "/my:myFields/my:field1", NamespaceManager). _
      SetValue("Running in a browser.")
ElseIf (Me.Application.Environment.IsMobile) Then
   CreateNavigator().SelectSingleNode( _
      "/my:myFields/my:field1", NamespaceManager). _
      SetValue("Running in a mobile browser.")
Else
   MessageBox.Show("This form is running in InfoPath.")
End If