20120903
通过代码了解C#中界面实现的过程:
主程序代码(主程序类AppStart继承于Application类):
using System; using System.Windows; // namespace CSUITest { class AppStart:Application { [STAThread] //所需的入口线程声明; static void Main(string[] args) { AppStart app = new AppStart(); //创建一个程序对象; app.Startup += AppStartUp; //添加程序启动事件; app.Exit += AppExit; //添加程序关闭事件; app.Run(new MainWindows("my no xml ui test")); //程序执行,界面显示。MainWindows为一个自定义显示类,其中包括处理函数及各种控件; } static void AppStartUp(object sender, StartupEventArgs e) { MessageBox.Show("App is starting!");
} static void AppExit(object sender, ExitEventArgs e) { MessageBox.Show("App is shutdowned!"); } } }
当然在上诉代码中app的执行顺序:Startup –> Run() –> Exit ;因此在那个部分实现那些过程按需求实现;
Window界面实现过程(MainWindows继承于Window):
using System; using System.Windows; // using System.Windows.Controls; //定义button等控件; using System.Windows.Input; //定义输入设备控制; namespace CSUITest { class MainWindows:Window { #region controls private Button btWindowExit = new Button(); #endregion public MainWindows(string title = "defalut name", int width = 600, int height = 400) {
//定义按钮属性;
#region controls Init btWindowExit.Height = 20; btWindowExit.Width = 100; btWindowExit.Content = "退出"; btWindowExit.Click += new RoutedEventHandler(btWidExit_Clicked); //绑定按钮点击处理函数; #endregion // this.AddChild(btWindowExit); //在主界面中添加按钮控件; // // #region 添加鼠标按键响应事件 this.MouseMove += new MouseEventHandler(Wind_MouseMove); this.KeyUp += new KeyEventHandler(Wind_KeyUp); this.MouseDown += new MouseButtonEventHandler(Wind_MouseDown); #endregion this.Title = title; this.WindowStartupLocation = WindowStartupLocation.CenterScreen; this.Height = height; this.Width = width;
this.Loaded += new RoutedEventHandler(MainWindows_Loaded); //窗口显示前;
this.Closed +=new EventHandler(MainWindows_Closed); //窗口消失后;
this.Show(); } private void btWidExit_Clicked(object sender, RoutedEventArgs e) { Application.Current.Shutdown(); } private void Wind_MouseMove(object sender, MouseEventArgs e) { this.Title = e.GetPosition(this).ToString(); } private void Wind_MouseDown(object sender, MouseButtonEventArgs e) { MessageBox.Show(e.ClickCount.ToString()); } private void Wind_KeyUp(object sender, KeyEventArgs e) { this.Title = e.Key.ToString(); } } }
类似于application的执行过程,windows也由类似的过程:既在窗口的显示前和关闭后的事件调用(消息路由)分别是loaded和closed属性;
备注:由于通过VS项目创建向导,直接利用其界面程序默认使用XMAL,因此在此利用创建一个控制台工程,在添加Windows界面所需的引用PresentationCore、PresentationFramework、System.Core和System.Xaml。
可以发现,对于复杂的界面编程,整个过程如果不依靠XMAL布局比较麻烦和繁琐.