Condividi tramite


Adding Custom My.Application Methods to C# Windows Forms Applications

In my last entry, I talked about how I loved extending My.Application in VB to create global methods available to my entire application. A reader mentioned that you can get much of the default functionality associated with the My class by using That. But what about adding your own global functionality?

You can easily create your own My.Application in a C# Windows Forms app. This provides a central location for application logging and other common tasks. In the following example, I describe how to do this to expose the DataDirectory property I wrote in a previous post, so that any form or class in your Windows Forms application can discover where the data directory for ClickOnce resides.

  1. Open Program.cs.

  2. Define a static class named My with a single property named Application:

     public static class My
    {
    private static MyApplication defaultInstance = new CountDownCSharp.MyApplication();

    public static MyApplication Application
    {
    get
    {
    return (defaultInstance);
    }
    }
    }

  3. Define MyApplication to contain all of the global methods and properties you'll need. 

        public class MyApplication
    {
    String _DataDirectory = null;

    public MyApplication()
    {
    }

    public string GetDataDirectory()
    {
    string _PathStr;
    if (ApplicationDeployment.IsNetworkDeployed)
    {
    _PathStr = WinForms.Application.UserAppDataPath;
    }
    else
    {
    _PathStr = WinForms.Application.ExecutablePath.Substring(0, WinForms.Application.ExecutablePath.LastIndexOf("\\"));
    if (!(Directory.Exists(_PathStr + "\\images")))
    {
    _PathStr = _PathStr + "[\\..\\](file://\\..\\)..";
    if (!(Directory.Exists(_PathStr + "\\images")))
    {
    throw new DirectoryNotFoundException("Cannot find directory " + _PathStr + "\\images. Fatal error.");
    }
    }
    }
    return (_PathStr);
    }

    public string DataDirectory
    {
    get
    {
    if ((_DataDirectory == null))
    {
    _DataDirectory = GetDataDirectory();
    return (_DataDirectory);
    }
    else
    {
    return (_DataDirectory);
    }
    }
    }