Click here to Skip to main content
Email Password   helpLost your password?

Introduction

While it’s running, every WPF application is represented by an instance of the System.Windows.Application class. This class tracks all the open windows in your application, decides when your application shuts down, and fires application events that you can handle to perform initialization and cleanup.
The Application class isn’t one of the more fascinating parts of WPF. However, because every WPF application uses the Application class, learning how it works is required reading. In this article, you’ll quickly get the essentials.

Note The System.Windows.Application class plays the same role in a WPF application as the System.Windows.Forms.Application class plays in a Windows Forms application. But Microsoft, always happy to reinvent the wheel, has given each one subtly different members and functionality.

Content  

The Application Life Cycle  

Application Task  

The Last World

The Application Life Cycle

In WPF, applications go through a straightforward life cycle. Shortly after your application begins, the application object is created. As your application runs, various application events fire, which you may choose to monitor. Finally, when the application object is released, your application ends.

Creating an Application Object  

If you want to do all the heavy lifting yourself, you can create an instance of the WPF Application class by hand. To do so, you must configure your application to start by running a shared Main() method. The following Program class shows an example—it includes a Main() method that creates a window named Window1 and fires up a new application:

Public Class Startup
     Inherits Application
           Shared Sub Main()
              ' Create the application.
              Dim app As New Application()
              ' Create the main window.
              Dim win As New Window1()
              ' Launch the application and show the main window.
              app.Run(win)
            End Sub
End Class

When you pass a window to the Application.Run() method, that window is set as the main window and exposed to your entire application through the application.MainWindow property.
The Run() method then fires the Application.Startup event and shows the main window.
When started in this way, your application continues running until the main window and every other window is closed. At that point, the Run() method returns, and any additional code in your Main() method is executed before the application winds down.

Note If you want to start your application using a Main() method, you need to designate the class that contains the Main() method as the startup object in Visual Studio. To do so, double-click the My Project node in the Solution Explorer. In the Application tab, remove the check mark next to the Enable Application Framework setting. You can then choose Sub Main in the Startup Object list. Ordinarily, you don’t need to take this
step, because Visual Studio creates the Main() method for you based on the XAML application template. You’ll learn about the application template in the next section.

Deriving a Custom Application Class

Although the approach shown in the previous section (instantiating the base Application class and calling the Run() method) works perfectly well, it’s not the pattern that Visual Studio uses when you create a new WPF application.
Instead, Visual Studio derives a custom class from the Application class. In a simple application, this approach has no meaningful effect. However, if you’re planning to handle application events, it provides a neater model, because you can place all your event handling code in the Application-derived class.
The model Visual Studio uses for the Application class is essentially the same as the
model it uses for the windows. The starting point is a XAML template, which is named Application.xaml by default. Here’s what it looks like:

<Application x:Class="Application"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     StartupUri="Window1.xaml">
</Application>

The Class attribute is used in XAML to create a class derived from the element. Thus, this markup creates a class that derives from System.Windows.Application, with (confusingly enough) the name Application. If you want, you can change the class name to something else.
The Application tag not only creates a custom application class, but it also sets the
StartupUri property to identify the XAML document that represents the main window. As a result, you don’t need to explicitly instantiate this window using code—the XAML parser will do it for you.
As with windows, the application class is defined in two separate portions that are fused together at compile time. The automatically generated portion isn’t visible in your project, but it contains the Main() entry point and the code for starting the application. It looks something like this:

Partial Public Class Application
     Inherits System.Windows.Application
        Public Shared Sub Main()
            Dim app As New Application
            app.InitializeComponent()
            app.Run()
        End Sub
       Public Sub InitializeComponent()
           Me.StartupUri = New System.Uri("Window1.xaml", System.UriKind.Relative)
       End Sub
End Class

If you’re really interested in seeing the custom application class that the XAML template creates, look for the Application.g.vb file in the obj\Debug folder inside your project directory.
The only difference between the automatically generated code shown here and a custom application class that you might create on your own is that the automatically generated class uses the StartupUri property instead of setting the MainWindow property or passing the main window as a parameter to the Run() method. You’re free to create a custom application class that uses this approach, so long as you use the same URI format. You need to create a relative Uri object that names a XAML document that’s in your project. (This XAML document is compiled and embedded in your application assembly as a BAML resource. The resource name is
the name of the original XAML file. In the previous example, the application contains a resource named Window1.xaml with the compiled XAML.)

Note The URI system you see here is an all-purpose way to refer to resources in your application.

The second portion of the custom application class is stored in your project in a file like Application.xaml.vb. It contains the event handling code you add. Initially, it’s empty aside from a comment:

Class Application
    ' Application-level events, such as Startup, Exit, and
    ' DispatcherUnhandledException can be handled in this file.
End Class

This file is merged with the automatically generated application code through the magic of partial classes.

Application Shutdown

Ordinarily, the Application class keeps your application alive as long as at least one window is still open. If this isn’t the behavior you want, you can adjust the Application.ShutdownMode.
If you’re instantiating your Application object by hand, you need to set the ShutdownMode property before you call Run(). If you’re using the Application.xaml file, you can simply set the ShutdownMode property in the XAML markup.
You have three choices for the shutdown mode, as listed in the next table:

ValueDescription
OnLastWindowCloseThis is the default behavior—your application keeps running as long as
there is at least one window in existence. If you close the main window,
the Application.MainWindow property still refers to the object that represents the closed window. (Optionally, you can use code to reassign the MainWindow property to point to a different window.)
OnMainWindowCloseThis is the traditional approach—your application stays alive only as long as the main window is open.
OnExplicitShutdownThe application never ends (even if all the windows are closed) unless you call Application.Shutdown(). This approach might make sense if your application is a front end for a long-running background task or if you just want to use more complex logic to decide when your application should close (at which point you’ll call the Application.Shutdown()
method).

Table 1 - Values from the Shutdown Mode Enumeration

For example, if you want to use the OnMainWindowClose approach and you’re using the Application.xaml file, you need to make this addition:

<Application x:Class="Application"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     StartupUri="Window1.xaml" ShutdownMode="OnMainWindowClose">
</Application>

Alternatively, you can apply the same setting through your project properties. To do so, double-click the My Project node in the Solution Explorer, choose the Application tab, and choose an option for the Shutdown Mode setting. You have three choices, which correspond to the values in the ShutdownMode enumeration.
No matter what shutdown method you choose, you can always use the Application.
Shutdown() method to end your application immediately. (Of course, when you call the Shutdown() method, your application doesn’t necessarily stop running right away. Calling Application.Shutdown() causes the Application.Run() method to return immediately, but there may be additional code that runs in the Main() method or responds to the Application.Exit event.)

Note When ShutdownMode is OnMainWindowClose and you close the main window, the Application object will automatically close all the other windows before the Run() method returns. The same is true if you call Application.Shutdown(). This is significant, because these windows may have event handling code that fires when they are being closed.

Application Events  

Initially, the Application.xaml.vb file doesn’t contain any code. Although no code is required, you can add code that handles application events. The Application class provides a small set of useful events. Table 2 lists the most important ones. It leaves out the events that are used solely for navigation applications

NameDescription
StartupOccurs after the Application.Run() method is called and just before the main window is shown (if you passed the main window to the Run() method). You can use this event to check for
any command-line arguments, which are provided as an array through the startupEventArgs.Args property. You can also use this event to create and show the main window (instead of using
the StartupUri property in the Application.xaml file).
ExitOccurs when the application is being shut down for any reason, just before the Run() method returns. You can’t cancel the shutdown at this point, although the code in your Main() method
could relaunch the application. You can use the Exit event to set the integer exit code that’s returned from the Run() method.
SessionEndingOccurs when the Windows session is ending—for example, when the user is logging off or shutting down the computer. (You can find out which one it is by examining the SessionEndingCancel-
EventArgs.ReasonSessionEnding property.) You can also cancel the shutdown by setting SessionEndingCancelEventArgs.Cancel
to True. If you don’t, WPF will call the Application.Shutdown() method when your event handler ends.
ActivatedOccurs when one of the windows in the application gets activated. This occurs when you switch from another Windows
program to this application. It also occurs the first time you show a window.
DeactivatedOccurs when a window in the application gets deactivated. This occurs when you switch to another Windows program.
DispatcherUnhandledExceptionOccurs when an unhandled exception occurs anywhere in your application (on the main application thread). (The application dispatcher catches these exceptions.) By responding to this
event, you can log critical errors, and you can even choose to neutralize the exception and continue running your application by setting the DispatcherUnhandledExceptionEventArgs.
Handled property to True. You should take this step only if you can be guaranteed that the application is still in a valid state and can continue.

WPF gives you several equivalent options for handling application events:
• You can use the AddHandler statement in your code.
• You can add the Handles clause to a method definition.
• You can set the corresponding event attribute in the Application.xaml file.
All of these options are equivalent. Unlike the events that take place in a WPF window (where the Handles clause sacrifices some capabilities), there’s no difference when dealing with application events.
For example, if you create this event handler to respond to unhandled exceptions:

Private Sub Application_DispatcherUnhandledException(ByVal sender As Object, _
       ByVal e As DispatcherUnhandledExceptionEventArgs)
       MessageBox.Show("An unhandled " & e.Exception.GetType().ToString() & _
       " exception was caught and ignored.")
       e.Handled = True
End Sub

you can connect to the Application.DispatcherUnhandled event by adding the Handles keyword:

Private Sub Application_DispatcherUnhandledException(ByVal sender As Object, _
      ByVal e As DispatcherUnhandledExceptionEventArgs) _
      Handles Me.DispatcherUnhandledException

Or you can connect it by adding the DispatcherUnhandledException attribute to the
Application tag in the Application.xaml file:

<Application x:Class="Application"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     StartupUri="Window1.xaml"
     DispatcherUnhandledException="Application_DispatcherUnhandledException">
</Application> 

Application Task  

Now that you understand how the Application object fits into a WPF application, you’re ready to take a look at how you can apply it to a few common scenarios. In the following sections, you’ll consider how you can process command-line arguments, support interaction between windows, add document tracking, and create a single-instance application.

Handling Command-Line Arguments  

To process command-line arguments, you react to the Application.Startup event. The arguments are provided as an array of strings through the StartupEventArgs.Args property. For example, imagine you want to load a document when its name is passed as a command-line argument. In this case, it makes sense to read the command-line arguments and perform the extra initialization you need. The following example implements this pattern by responding to the Application.Startup event. It doesn’t set the Application.StartupUri property
at any point—instead the main window is instantiated using code.

Public Class Application
   Private Sub Application_Startup(ByVal sender As Object, _
       ByVal e As System.Windows.StartupEventArgs) Handles Me.Startup
       ' Create, but don't show the main window.
       Dim win As New FileViewer()
       If e.Args.Length > 0 Then
           Dim file As String = e.Args(0)
           If System.IO.File.Exists(file) Then
             ' Configure the main window.
             win.LoadFile(file)
           End If
       Else
           ' (Perform alternate initialization here when
           ' no command-line arguments are supplied.)
       End If
      ' This window will automatically be set as the Application.MainWindow.
       win.Show()
   End Sub
End Class

This method initializes the main window, which is then shown when the
Application_Startup() method ends. This code assumes that the FileViewer class has a public method (that you’ve added) named LoadFile(). Here’s one possible example, which simply reads (and displays) the text in the file you’ve identified:

Public Class FileViewer
     ...
     Public Sub LoadFile(ByVal path As String)
           Me.Content = File.ReadAllText(path)
           Me.Title = path
     End Sub
End Class

Note If you’re a seasoned Windows Forms programmer, the code in the LoadFile() method looks a little strange. It sets the Content property of the current Window, which determines what the window displays in its client area. Interestingly enough, WPF windows are actually a type of content control (meaning they derive from the ContentControl class). As a result, they can contain (and display) a single object. It’s up to you whether that object is a string, a control, or (more usefully) a panel that can host multiple controls.  

Accessing the Current Application

You can get the current application instance from anywhere in your application using the shared Application.Current property. This allows rudimentary interaction between windows, because any window can get access the current Application object and through that obtain a reference to the main window.

Dim main As Window = Application.Current.MainWindow
MessageBox.Show("The main window is " & main.Title)

Of course, if you want to access any methods, properties, or events that you’ve added to your custom main window class, you need to cast the window object to the right type. If the main window is an instance of a custom MainWindow class, you can use code like this:

Dim main As MainWindow = CType(Application.Current.MainWindow, MainWindow)
main.DoSomething()

A window can also examine the contents of the Application.Windows collection, which provides references to all the currently open windows:

For Each window As Window In Application.Current.Windows
     MessageBox.Show(window.Title & " is open.")
Next 

In practice, most applications prefer to use a more structured form of interaction between windows. If you have several long-running windows that are open at the same time and they need to communicate in some way, it makes more sense to hold references to these windows in a custom application class. That way you can always find exactly the window you need.
Similarly, if you have a document-based application, you might choose to create a collection that tracks document windows but nothing else. The next section considers this technique.

Note Windows (including the main window) are added to the Windows collection as they’re shown, and they’re removed when they’re closed. For this reason, the position of windows in the collection may change, and you can’t assume you’ll find a specific window object at a specific position.

Interacting Between Windows  

As you’ve seen, the custom application class is a great place to put code that reacts to different application events. There’s one other purpose that an Application class can fill quite nicely: storing references to important windows so one window can access another.

Tip This technique makes sense when you have a modeless window that lives for a long period of time and might be accessed in several different classes (not just the class that created it). If you’re simply showing a modal dialog box as part of your application, this technique is overkill. In this situation, the window won’t exist for very long, and the code that creates the window is the only code that needs to access it.For example, imagine you want to keep track of all the document windows that your
application uses. To that end, you might create a dedicated collection in your custom application class. Here’s an example that uses a generic List collection to hold a group of custom window objects. In this example, each document window is represented by an instance of a class named Document:

Public Class ApplicationCore
      Private _documents As New List(Of Document)()
         Public Property Documents() As List(Of Document)
          Get
            Return _documents
          End Get
          Set(ByVal value As List(Of Document))
            _documents = value
          End Set
        End Property
     End Class 

Notice that the application class has been named ApplicationCore instead of the standard Application, which avoids confusion with the System.Windows.Application base class.
Now, when you create a new document, you simply need to remember to add it to the Documents collection. Here’s an event handler that responds to a button click and does the deed:

Private Sub cmdCreate_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
     Dim doc As New Document() 
     doc.Owner = Me
     doc.Show()
     CType(Application.Current, ApplicationCore).Documents.Add(doc)
End Sub

Alternatively, you could respond to an event like Window.Loaded in the Document class to make sure the document object always registers itself in the Documents collection when it’s created.

Note This code also sets the Window.Owner property so that all the document windows are displayed “on top” of the main window that creates them.

Now you can use that collection elsewhere in your code to loop over all the documents and use public members. In this case, the Document class includes a custom SetContent() method that updates its display:

Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
     Dim app As ApplicationCore = CType(Application.Current, ApplicationCore) 
     For Each doc As Document In app.Documents 
        doc.SetContent("Refreshed at " & DateTime.Now.ToLongTimeString() & ".") 
     Next
End Sub 

Figure 1 demonstrates this application. The actual end result isn’t terribly impressive, but the interaction is worth noting—it demonstrates a safe, disciplined way for your windows to interact through a custom application class. It’s superior to using the Windows property, because it’s strongly typed, and it holds only Document windows (not a collection of all the windows in your application). It also gives you the ability to categorize the windows in another, more useful way—for example, in a Dictionary collection with a key name for easy lookup. In a document-based application you might choose to index windows in a collection
by file name.

Figure 1 - Allowing windows to interact

Note When interacting between windows, don’t forget your object-oriented smarts—always use a layer of custom methods, properties, and events that you’ve added to the window classes. Never expose the fields or controls of a form to other parts of your code. If you do, you’ll quickly wind up with a tightly coupled interface where one window reaches deep into the inner workings of another, and you won’t be able to enhance
either class without breaking the murky interdependencies between them.

Single-Instance Applications 

Ordinarily, you can launch as many copies of a WPF application as you want. In some scenarios, this design makes perfect sense. However, in other cases it’s a problem, particularly when building document-based applications.
For example, consider Microsoft Word. No matter how many documents you open (or how you open them), only a single instance of winword.exe is loaded at a time. As you open new documents, they appear in the new windows, but a single application remains in control of all the document windows. This design is the best approach if you want to reduce the overhead of your application, centralize certain features (for example, create a single print queue manager), or integrate disparate windows (for example, offer a feature that tiles all the currently open document windows next to each other).
WPF doesn’t provide a native solution for single-instance applications, but you can use several workarounds. The basic technique is to check whether another instance of your application is already running when the Application.Startup event fires. The simplest way to do this is to use a systemwide mutex (a synchronization object provided by the operating system that allows for interprocess communication). This approach is simple but limited—most significantly, there’s no way for the new instance of an application to communicate with the existing instance. This is a problem in a document-based application, because the new instance may need to tell the existing instance to open a specific document, if it’s passed on the command
line. (For example, when you double-click a .doc file in Windows Explorer and Word is already running, you expect Word to load the requested file.) This communication is more complex, and it’s usually performed through remoting or Windows Communication Foundation (WCF).
A proper implementation needs to include a way to discover the remoting server and use it to transfer command-line arguments.
But the simplest approach, and the one that’s currently recommended by the WPF team, is to use the built-in support that’s provided in Windows Forms and tailored to Visual Basic applications. This approach handles the messy plumbing behind the scenes.
So, how can you use a feature that’s designed for Windows Forms to manage a WPF application?
Essentially, the old-style application class acts as a wrapper for your WPF application class. When your application is launched, you’ll create the old-style application class, which will then create the WPF application class. The old-style application class handles the instance management, while the WPF application class handles the real application.

Figure 2 shows how these parts interact.

Figure 2 - Wrapping the WPF Application with a WindowsFormsApplicationBase

The first step to use this approach is to derive a custom class from the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class. This
class provides three important members that you use for instance management:
• The IsSingleInstance property enables a single-instance application. You set this
property to True in the constructor.
• The OnStartup() method is triggered when the application starts. You override this
method and create the WPF application object at this point.

Note Ordinarily, all applications that derive from WindowsFormsApplicationBase designate a main form.However, your application uses the WPF model, so it won’t include any forms. To prevent an error, you mustreplace the default startup logic by overriding OnStartup(). It’s not enough to simply handle the Startup event.

• The StartupNextInstance event is fired when another instance of the application starts up. This event provides access to the command-line arguments. At this point, you’ll probably call a method in your WPF application class to show a new window but not create another application object.
Here’s the code for the custom class that’s derived from WindowsFormsApplicationBase: 

Public Class SingleInstanceApplicationWrapper
Inherits 
     _Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
     Public Sub New()
    ' Enable single-instance mode.
     Me.IsSingleInstance = True
     End Sub
    ' Create the WPF application class.
     Private app As WpfApp
     Protected Overrides Function OnStartup(ByVal eventArgs As _
             Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) As Boolean
             app = New WpfApp()
             app.Run()
             Return False
     End Function
    ' Direct multiple instances
    Private Sub StartupNextInstance(ByVal sender As Object, ByVal e As _
       Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) _
          Handles Me.StartupNextInstance
          If e.CommandLine.Count > 0 Then
               app.ShowDocument(e.CommandLine(0))
          End If
       End Sub
End Class

When the application starts, this class creates an instance of WpfApp, which is a custom WPF application class (a class that derives from  System.Windows.Application). The WpfApp class includes some startup logic that shows a main window, along with a custom ShowDocument() window that loads a document window for a given file. Every time a file History Keep a running update of any changes or improvements you've made here.  

name is passed to SingleInstanceApplicationWrapper through the command line,
SingleInstanceApplicationWrapper calls WpfApp.ShowDocument().
Here’s the code for the WpfApp class:

Public Class WpfApp
  Inherits System.Windows.Application
  Private Sub Application_Startup(ByVal sender As Object, _
        ByVal e As System.Windows.StartupEventArgs) _
           Handles Me.Startup
           ' Load the main window.
            Dim list As New DocumentList()
            Me.MainWindow = list
            list.Show()
            ' Load the document that was specified as an argument.
            If e.Args.Length > 0 Then
                 ShowDocument(e.Args(0))
            End If
   End Sub
   Public Sub ShowDocument(ByVal filename As String)
      Try
         Dim doc As New Document()
         Dim docRef As New DocumentReference(doc, filename)
         doc.LoadFile(docRef)
         doc.Owner = Me.MainWindow
         doc.Show() 
         doc.Activate()
      Catch
         MessageBox.Show("Could not load document.")
      End Try
   End Sub
End Class

The only missing detail now (aside from the DocumentList and Document windows)
is the entry point for the application. Because the application needs to create the
SingleInstanceApplicationWrapper class before the App class, the application needs to start with a traditional Main() method, rather than an Application.xaml file. Here’s the code you need:

Public Class Startup
      Public Shared Sub Main(ByVal args As String())
         Dim wrapper As New SingleInstanceApplicationWrapper()
         wrapper.Run(args)
      End Sub
End Class 

These three classes—SingleInstanceApplicationWrapper, WpfApp, and Startup—form the basis for a single-instance WPF application. Using these bare bones, it’s possible to create a more sophisticated example. For example, the code for this article modifies the WpfApp class so it maintains a list of open documents (as demonstrated earlier). Using WPF data binding , the DocumentList window displays the currently open documents. Figure 3 shows an example with three open documents. 

Figure 3 - A Single-instance application with a central window

Finally, the SingleInstanceApplication example includes a FileRegistrationHelper class that registers a file extension using the classes in the Microsoft.Win32 namespace:

Dim extension As String = ".testDoc"
Dim title As String = "SingleInstanceApplication"
Dim extensionDescription As String = "A Test Document"
FileRegistrationHelper.SetFileAssociation( _
extension, title & "." & extensionDescription)

This code needs to be executed only once. After the registration is in place, every time you double-click a file with the extension .testDoc, the SingleInstanceApplication is started, and the file is passed as a command-line argument. If the SingleInstanceApplication is already running, the SingleInstanceApplicationWrapper.StartupNextInstance event is triggered, and
the new document is loaded by the existing application.
nNote Single-instance application support will eventually make its way to WPF in a future version. For now, this workaround provides the same functionality with only a little more work required.


 
WINDOWS VISTA AND UAC

File registration is a task that’s usually performed by a setup program. One problem with including it in your application code is that it requires elevated permissions that the user running the application might not have.
This is particularly a problem with the User Account Control (UAC) feature in Windows Vista. In fact, by default this code will fail with a security-related exception.
In the eyes of UAC, all applications have one of three run levels:
• asInvoker. The application inherits the process token of the parent process (the process that launched
it). The application won’t get administrator privileges unless the user specifically requests them, even if
the user is logged on as an administrator. This is the default.
• requireAdministrator. If the current user is a member of the Administrators group, a UAC confirmation dialog box appears. Once the user accepts this confirmation, the application gets administrator privileges.
If the user is not a member of the Administrators group, a dialog box appears where the user can enter the user name and password of an account that does have administrator privileges.
• highestAvailable. The application gets the highest privileges according to its group membership. For example, if the current user is a member of the Administrators group, the application gets administrator privileges (once the user accepts the UAC confirmation). The advantage of this run level is that the
application will still run if administrator privileges aren’t available, unlike requireAdministrator.
Ordinarily, your application runs with the asInvoker run level. To request administrator privileges, you must right-click the application EXE file and choose Run As Administrator when you start it. To get administrator privileges when testing your application Visual Studio, you must right-click the Visual Studio shortcut and choose Run As Administrator.
If your application needs administrator privileges, you can choose to require them with the requireAdministrator run level or request them with the highestAvailable run level. Either way, you need to create a manifest—a file with a block of XML that will be embedded in your compiled assembly. To edit the
manifest for your application, double-click the My Project node. Then, on the Application tab, click the View UAC Settings button.
The content of the manifest file is the relatively simple block of XML shown here:

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0"
      xmlns="urn:schemas-microsoft-com:asm.v1"
      xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" 
      xmlns:asmv2="urn:schemas-microsoft-com:asm.v2">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
      <requestedExecutionLevel level="asInvoker" />
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly> 

To change the run level, simply modify the level attribute of the <requestedExcutionLevel> element.
Valid values are asInvoker, requireAdministrator, and highestAvailable.
In some cases, you might want to request administrator privileges in specific scenarios. In the file registration example, you might choose to request administrator privileges only when the application is run for the first time and needs to create the registration. This allows you to avoid unnecessary UAC warnings. The easiest way to implement this pattern is to put the code that requires higher privileges in a separate executable, which you can then call when necessary.


The Last World  

In this article, you took a quick look at the WPF application model. To manage a simple WPF application, you need to do nothing more than create an instance of the Application class and call the Run() method. However, most applications go further and derive a custom class from the Application class. And as you saw, this custom class is an ideal tool for handling application events and an ideal place to track the windows in your application or implement a single-instance pattern.
You haven’t quite plumbed the full reaches of the Application class—there’s still a
Resources collection to consider, where you can define objects you want to reuse throughout your application, like styles that can be applied to controls in multiple windows.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalwtf
Jouketje
3:44 13 Aug '09  
Weird how I just bought a book you didn't write with a chapter in it with the exact same content as this article. Even the images are the same. You should at least mention you copied this..
GeneralMy vote of 2
Sacha Barber
10:46 10 Aug '09  
copied from all over


Last Updated 11 Aug 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010