DotNet · 2022年5月2日

在C#中使用My功能

在C#中使用My.Application

要使用My.Application,必须要继承System.Windows.Forms.WindowsFormsApplicationBase
(该类位于Microsoft.VisualBasic.dll中)。继承之后我们要做几件事情,首先书写构造函数初始化MyApplication类,在Visual
Basic中这些设置均为IDE生成,而C#则需要手工书写。然后重写OnCreateMainForm方法,这个方法设定了当前应用程序的主窗体。接下来书写My类,让他提供对MyApplication类的全局访问点。最后改写Main,在其中执行My.Application.Run()代替原来的
Application.Run(),具体做法如下。


namespace WindowsApplication2.Properties
{
    
public class MyApplication : WindowsFormsApplicationBase
    
{
        
public MyApplication() : base(AuthenticationMode.Windows)
        
{
            IsSingleInstance 
= false;
            EnableVisualStyles 
= true;
            ShutdownStyle 
= ShutdownMode.AfterMainFormCloses;
        }



        
protected override void OnCreateMainForm()
        
{
            
//Sepecify the main form of your project
            MainForm = new WindowsApplication2.Form1();
        }


    }


    
public static class My
    
{
        
private static MyApplication _Application;
        
private static object syncRoot = new object();

        
public static MyApplication Application
        
{
            
get {
                
if (_Application == null)
                
{
                    
lock (syncRoot)
                    
{
                        
if (_Application == null)
                        
{
                            _Application 
= new MyApplication();
                        }

                    }
 // end lock
                }
 // end if
                return _Application; 
            }
 // end get
        }


    }

}
 

修改Main函数

[STAThread]
static void Main()
{
    
// Application.EnableVisualStyles();
    
// Application.EnableRTLMirroring();
    
// Application.Run(new Form1());
    Properties.My.Application.Run();
}
 

 

在C#中使用My.Computer

要使用My.Computer我们无需像Application那样费劲了。Visual
Basic的设计者将大部分供能放到了System的自命名空间中,可以很自然地使用他们:

My中的名称 System中的名称
My.Computer.FileSystem System.IO.FileSystem
My.Application.AssemblyInfo System.Reflection.AssemblyInfo*
My.Computer.KeyBoard System.Windows.Forms.KeyBoard
My.Computer.Mouse Sysetm.Widnows.Forms.Mouse

注:System.Reflecton.AssemblyInfo只是My.Applicaton.AssemblyInfo的类型。

当然这不如Visual Basic中那样丰富,但是一般应用有FileSystem就足够了,其他功能用.NET
Framework原本的方法也很简单。要注意,尽管这些类分散在System的各个字命名空间中,但是全部都位于
Microsoft.VisualBasic.dll中,需要引用它才能使用。

在C#中使用My.Resources和My.Settings

一个好消息是,C#也内置了这两样功能,只要把My换成Properties就可以使用了,和Visual
Basic一样方便。但是My.User、My.Forms和My.WebServices是真的没有了,要实现他们的功能,需要完全手工编码。

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞