Application类---管理应用程序

一,Application类的启动和停止.

  1,设定启动方式,可以在两个启动的Main函数中选择启动函数.

image

2,可以设定窗口关闭的方式:

image

3,事件说明:

StartUp:传递命令行参数,在Run运行后,窗口运行前.

 private void TestApp_Startup(object sender, StartupEventArgs e)
        {
            MessageBox.Show(e.Args[0]);
        }

Exit:传递一个ShutDown传递的参数

  private void TestApp_Exit(object sender, ExitEventArgs e)
        {
            MessageBox.Show(e.ApplicationExitCode.ToString());
        }

4,事件列表

image

5,使用触发程序:事件+触发加On来进行重写.可以执行这个函数来触发事件.

 protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);//一般触发对应事件.
            MessageBox.Show("overrided StartUp");//自定义内容
        }

6,显示初始窗口的方法:

image


       使用代码实现:

SplashScreen splashScreen = new SplashScreen("制胶机.png");
            splashScreen.Show(false);//false则由代码控制何时消失.
            splashScreen.Close( new TimeSpan(1000));

二,单实列应用程序的架构:

       1,单实列应用程序的框架:

            image

     2,引用Microsoft.VisualBasic.dll程序集

  •             创建启动类:
     public class Startup
        {
            [STAThread]
            public static void Main(string[] args)
            {
                SingleInstanceApplicationWrapper wrapper = new SingleInstanceApplicationWrapper();
                wrapper.Run(args);
            }
        }
  •    在启动类中,创建一个单实列的应用程序类:
    public class SingleInstanceApplicationWrapper :
            Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
        {
            public SingleInstanceApplicationWrapper()
            {
                // Enable single-instance mode.
                this.IsSingleInstance = true;
            }
    
            // Create the WPF application class.
            private WpfApp app;
            protected override bool OnStartup(//首次启动创建应用程序,并且注册表注册
                Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
            {
                string extension = ".testDoc";
                string title = "SingleInstanceApplication";
                string extensionDescription = "A Test Document";
                // Uncomment this line to create the file registration.
                // In Windows Vista, you'll need to run the application
                // as an administrator.
                FileRegistrationHelper.SetFileAssociation(
                  extension, title + "." + extensionDescription);
    
                app = new WpfApp();
                app.Run();
    
                return false;
            }
    
            // Direct multiple instances
            protected override void OnStartupNextInstance(//再次启动的时候,(二次启动,
    //进行自定义的文档显示操作.
                Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs e)
            {
                if (e.CommandLine.Count > 0)
                {
                    app.ShowDocument(e.CommandLine[0]);
                }
            }
        }
  • 创建WPF app类
public class WpfApp : System.Windows.Application
    {
        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {//重载启动触发函数.
            base.OnStartup(e);

            // Load the main window.
            DocumentList list = new DocumentList();
            this.MainWindow = list;
            list.Show();//显示主窗体

            // Load the document that was specified as an argument.
            if (e.Args.Length > 0) ShowDocument(e.Args[0]);//显示分文档.
        }

        // An ObservableCollection is a List that provides notification
        // when items are added, deleted, or removed. It's preferred for data binding.
        private ObservableCollection<DocumentReference> documents =
            new ObservableCollection<DocumentReference>();//一个带通知的集合类.
        public ObservableCollection<DocumentReference> Documents
        {
            get { return documents; }
            set { documents = value; }
        }

        public void ShowDocument(string filename)
        {
            try
            {
                Document doc = new Document();
                DocumentReference docRef = new DocumentReference(doc, filename);
                doc.LoadFile(docRef);   //调用doc窗体方法显示文件内容.
                doc.Owner = this.MainWindow;//设定其主体.
                doc.Show();
                doc.Activate();//使其成为活动窗口.
                Documents.Add(docRef);//在其中添加信息.并且通知到主窗口.
            }
            catch
            {
                MessageBox.Show("Could not load document.");
            }
        }
    }
  • 这里的一个问题是如
  • namespace SingleInstanceApplication
    {
        /// <summary>
        /// Interaction logic for DocumentList.xaml
        /// </summary>
    
        public partial class DocumentList : System.Windows.Window
        {
            public DocumentList()
            {
                InitializeComponent();
    
                // Show the window names in a list.
                lstDocuments.DisplayMemberPath = "Name";
                lstDocuments.ItemsSource = ((WpfApp)Application.Current).Documents;
            }
        }
    }
  • 何将显示和数据绑定: 利用数据绑定功能.将listbox的源绑定到了一个集合的某个元素上.
  • 研究下注册表关联启动函数:

           如何用程序关联某个后缀的文档到其注册表之中?使用该函数创建注册表的子项和名值对. valueName=0,表示默认.

 private static void SetValue(RegistryKey root, string subKey, object keyValue, string valueName)
        {
            bool hasSubKey = ((subKey != null) && (subKey.Length > 0));
            RegistryKey key = root;

            try
            {
                if (hasSubKey) key = root.CreateSubKey(subKey);
                key.SetValue(valueName, keyValue);
            }
            finally
            {
                if (hasSubKey && (key != null)) key.Close();
            }
        }

          1,创建了一个.testdoc 子项:

             image

         2,创建了一个关联:

image

         3,创建了一个icon关联

image

        4, 创建一个Applications 关联项


image

整体程序如下://用于创建关联当前应用程序和某个后缀名.

public class FileRegistrationHelper
    {
        public static void SetFileAssociation(string extension, string progID)
        {
            // Create extension subkey
            SetValue(Registry.ClassesRoot, extension, progID);

            // Create progid subkey
            string assemblyFullPath = System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", @"\");
            StringBuilder sbShellEntry = new StringBuilder();
            sbShellEntry.AppendFormat("\"{0}\" \"%1\"", assemblyFullPath);
            SetValue(Registry.ClassesRoot, progID + @"\shell\open\command", sbShellEntry.ToString());
            StringBuilder sbDefaultIconEntry = new StringBuilder();
            sbDefaultIconEntry.AppendFormat("\"{0}\",0", assemblyFullPath);
            SetValue(Registry.ClassesRoot, progID + @"\DefaultIcon", sbDefaultIconEntry.ToString());

            // Create application subkey
            SetValue(Registry.ClassesRoot, @"Applications\" + Path.GetFileName(assemblyFullPath), "", "NoOpenWith");
        }

        private static void SetValue(RegistryKey root, string subKey, object keyValue)
        {
            SetValue(root, subKey, keyValue, null);
        }
        private static void SetValue(RegistryKey root, string subKey, object keyValue, string valueName)
        {
            bool hasSubKey = ((subKey != null) && (subKey.Length > 0));
            RegistryKey key = root;

            try
            {
                if (hasSubKey) key = root.CreateSubKey(subKey);
                key.SetValue(valueName, keyValue);
            }
            finally
            {
                if (hasSubKey && (key != null)) key.Close();
            }
        }
    }

另外,当使用文档关联的时候,打开文档的路径就是第一个参数.


三 提示权限的应用程序清单文件:

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <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="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>


四,程序集资源

          1, 如何生成程序集的资源? 在文件上设定resource即可,然后会生成一个资源文件:

其中,资源文件之类的都在obj/debug/文件夹下面:

image

2,检索资源:

  • 使用Application.GetResourceStream(new uri(“images/winter.jpg”,urikend.Relative));
StreamResourceInfo sri = Application.GetResourceStream(new Uri("images/tempsnip.jpg", UriKind.Relative));
            MessageBox.Show(sri.ContentType);
            Stream str = sri.Stream;

3,使用另一种方式获取资源

Assembly assembly = Assembly.GetAssembly(this.GetType());
           string resourceName = assembly.GetName().Name + ".g";//注意 Name()后面的Name不可少.
           ResourceManager rm = new ResourceManager(resourceName, assembly);
           using (
                ResourceSet set = rm.GetResourceSet(CultureInfo.InvariantCulture, true, true)
                )

          {

              foreach(DictionaryEntry res in set)
               {
                   MessageBox.Show(res.Value.ToString());
               }

          }

          其中:集合里面 key 是 路径  Value 是一个 非托管Stream对象.代表资源的字节流.

4,使用专有类访问资源:

比如 <Image Source = “Images/Blue hills.jpg”></Image>

      或者使用

      img.Source = new BitmapImage(new Uri(“images/winter.jpg”,UriKind.Relative));

    pack://application:,,,/+ images/winter.jpg.

5,内容文件 ;将文件设为content,并且选择始终复制.则可以像资源文件一样使用它.



6,本地化(略).

猜你喜欢

转载自www.cnblogs.com/frogkiller/p/12916294.html