最近,我給一家公司做了個電梯多媒體軟件,該軟件使用C#編寫,現在我將其中遇到的問題及其解決方法總結一下,以便下次再遇到同樣的問題可以快速解決;同時,也給博友分享一下,共同學習,共同提高。
1、Question:關閉窗體時出現“執行CreateHandle()時無法調用值Dispose()”的錯誤,如下圖所示:
Answer:原因是當前窗體的句柄還未創建完成,還存在CreateHandle()事件,還不能回收垃圾,還不能直接關閉窗體。
在執行窗體的Close方法時,加入判斷語句,如下:
if ( !IsHandleCreated) { this.Close(); }
2、Question:C#窗體間相互調用及數據傳遞方法
Answer:當我們在一個主窗體MainForm中生成一個窗體Form1,而又需要將窗體Form1中的數據傳給MainForm,此時就涉及到窗體間的相互調用。
1)當我們在主窗體MainForm中生成窗體Form1時,采用模式窗體,將MainForm設為Form1的父窗體,在Form1中調用MainForm時直接獲取其父窗體即可:
//MainForm中 Form1 form1 = new Form1(); form1.ShowDialog(this); //Form1中 MainForm mainform = (MainForm)this.Owner; mainform.BackColor = Color.Black; mainform.button1.BackColor = Color.Blue;
2)使用回調對象的方法:
//MainForm中 Form1 form1 = new Form1(); form1.mainform = this; form1.Show(); //Form1中 public MainForm mainform = new MainForm(); mainform.BackColor = Color.Black; mainform.button1.BackColor = Color.Blue;
3、Question:局域網內文件的傳輸
Answer:下面列舉幾種我嘗試的局域網內文件傳輸的方法:
1)文件復制至共享文件夾:引用Microsoft.VisualBasic.dll,調用FileSystem類的FileCopy方法
2)FTP協議
4、Question:C/S模式中的網絡通信(進程間通信)
Answer:Socket
5、Question:播放視頻
Answer:COM組件Windows Media Player
在C# .NET Windows應用程序中做視頻播放,首先要用到COM組件中的WMP控件(Windows Media Player)。下面主要講述在VS2010中WinForm窗體WMP控件的使用。
(1)在建好WinForm窗體后首先應添加COM組件Windows Media Player的引用。
(2)添加引用后,會建立其對象
private AxWMPLib.AxWindowsMediaPlayer axWindowsMediaPlayer;
其初始化代碼如下所示:
//
// axWindowsMediaPlayer
//
this.axWindowsMediaPlayer.Enabled = true;
this.axWindowsMediaPlayer.Location = new System.Drawing.Point(0, 0); this.axWindowsMediaPlayer.Name = "axWindowsMediaPlayer"; this.axWindowsMediaPlayer.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWindowsMediaPlayer.OcxState"))); this.axWindowsMediaPlayer.Size = new System.Drawing.Size(400, 300); this.axWindowsMediaPlayer.TabIndex = 0;
(3)設置其循環播放模式
this.axWindowsMediaPlayer.settings.setMode("loop", true);//循環播放
(4)播放列表操作
axWindowsMediaPlayer.currentPlaylist.clear();//清空 axWindowsMediaPlayer.currentPlaylist.appendItem(axWindowsMediaPlayer.newMedia("test.mp4"));//添加
(5)播放器控制
axWindowsMediaPlayer.Ctlcontrols.play();//播放
(6)Windows Media Player控件的詳細說明:
[基本屬性]
- URL:string 可以指定媒體位置
- enableContextMenu:Boolean 顯示/不顯示播放位置的右鍵菜單
- fullScreen:boolean 全屏顯示
- stretchToFit:boolean 非全屏狀態時是否伸展到最佳大小
- uMode:string 播放器的模式,full:有下面的控制條; none:只有播放部份沒有控制條
- playState:integer 當前控件狀態,狀態變化時會觸發OnStatusChange事件,其值如下所示:
Value State Description 0 Undefined Windows Media Player is in an undefined state.(未定義) 1 Stopped Playback of the current media item is stopped.(停止) 2 Paused Playback of the current media item is paused. When a media item is paused, resuming playback begins from the same location.(停留) 3 Playing The current media item is playing.(播放) 4 ScanForward The current media item is fast forwarding. 5 ScanReverse The current media item is fast rewinding. 6 Buffering The current media item is getting additional data from the server.(轉換) 7 Waiting Connection is established, but the server is not sending data. Waiting for session to begin.(暫停) 8 MediaEnded Media item has completed playback. (播放結束) 9 Transitioning Preparing new media item. 10 Ready Ready to begin playing.(准備就緒) 11 Reconnecting Reconnecting to stream.(重新連接)
[controls]
可通過WindowsMediaPlayer.controls對播放器進行控制並取得相關的一些信息:
- controls.play; 播放
- controls.stop; 停止
- controls.pause; 暫停
- controls.currentPosition:Double 當前播放進度
- controls.currentPositionString:string 時間格式的字符串 “0:32″
[currentMedia]
可以通過WindowsMediaPlayer.currentMedia取得當前媒體的信息
- currentMedia.duration Double 總長度
- currentMedia.durationString 時間格式的字符串 “4:34″
[settings]
可以通過WindowsMediaPlayer.settings對播放器進行設置,包括音量和聲道等。
- settings.volume:integer 音量 (0-100)
- settings.balance:integer 聲道,通過它應該可以進行立體聲、左聲道、右聲道的控制。
6、Question:獲取並顯示天氣信息
Answer:添加Web服務引用(http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx)
(1)建好WinForm項目后,添加服務引用
(2)獲取天氣的核心代碼:
private string[] MyGetWeather() { weatherInfos = new string[]{""};//length: 32 string try { MyWeatherWS.WeatherWS weather = new MyWeatherWS.WeatherWS(); weatherInfos = weather.getWeather(strWeatherCity, ""); return weatherInfos; } catch (Exception ex) { MessageBox.Show(ex.Message + "\n遠程網絡連接失敗!", "網絡錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning); return weatherInfos; } }
(3)關於WeatherWS的使用,參考http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx
7、Question:INI配置文件操作
Answer:
1)調用系統函數GetPrivateProfileString()和WritePrivateProfileString()等
(1)導入庫
[DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
(2)調用函數讀寫ini配置文件
//讀 StringBuilder strCom = new StringBuilder(255); GetPrivateProfileString("串口參數", "端口", "", strCom, 255, "Setting.ini"); //寫 WritePrivateProfileString("串口參數", "端口", "COM3", "Setting.ini");
2)配置文件操作組件:SharpConfig
SharpConfig 是 .NET 的 CFG/INI 配置文件操作組件。
配置文件示例(sample.cfg):
[General] # a comment SomeString = Hello World! SomeInteger = 10 # an inline comment SomeFloat = 20.05 ABoolean = true
C#代碼示例:
Configuration config = Configuration.LoadFromFile( "sample.cfg" ); Section section = config["General"]; string someString = section["SomeString"].Value; int someInteger = section["SomeInteger"].GetValue<int>(); float someFloat = section["SomeFloat"].GetValue<float>();
上述SharpConfig參考http://www.oschina.net/p/sharpconfig。
8、Question:獲取並顯示時間日期
Answer:調用DateTime.Now對象的方法
//獲取時間 DateTime.Now.ToLongTimeString().ToString(); // 16:16:16 //獲取日期 DateTime.Now.ToLongDateString().ToString(); // 2015年9月5日 DateTime.Now.ToShortDateString().ToString(); // 2015-9-5 DateTime.Now.ToString("yyyy-MM-dd"); // 2015-09-05
9、Question:ToString()格式
Answer:Int.ToString("Format"),Format如下所示:
10、Question:String方法
Answer:如下所示

string s = ""; //(1)字符訪問(下標訪問s[i]) s = "ABCD"; Console.WriteLine(s[0]); // 輸出"A"; Console.WriteLine(s.Length); // 輸出4 Console.WriteLine(); //(2)打散為字符數組(ToCharArray) s = "ABCD"; char[] arr = s.ToCharArray(); // 把字符串打散成字符數組{'A','B','C','D'} Console.WriteLine(arr[0]); // 輸出數組的第一個元素,輸出"A" Console.WriteLine(); //(3)截取子串(Substring) s = "ABCD"; Console.WriteLine(s.Substring(1)); // 從第2位開始(索引從0開始)截取一直到字符串結束,輸出"BCD" Console.WriteLine(s.Substring(1, 2)); // 從第2位開始截取2位,輸出"BC" Console.WriteLine(); //(4)匹配索引(IndexOf()) s = "ABCABCD"; Console.WriteLine(s.IndexOf('A')); // 從字符串頭部開始搜索第一個匹配字符A的位置索引,輸出"0" Console.WriteLine(s.IndexOf("BCD")); // 從字符串頭部開始搜索第一個匹配字符串BCD的位置,輸出"4" Console.WriteLine(s.LastIndexOf('C')); // 從字符串尾部開始搜索第一個匹配字符C的位置,輸出"5" Console.WriteLine(s.LastIndexOf("AB")); // 從字符串尾部開始搜索第一個匹配字符串BCD的位置,輸出"3" Console.WriteLine(s.IndexOf('E')); // 從字符串頭部開始搜索第一個匹配字符串E的位置,沒有匹配輸出"-1"; Console.WriteLine(s.Contains("ABCD")); // 判斷字符串中是否存在另一個字符串"ABCD",輸出true Console.WriteLine(); //(5)大小寫轉換(ToUpper和ToLower) s = "aBcD"; Console.WriteLine(s.ToLower()); // 轉化為小寫,輸出"abcd" Console.WriteLine(s.ToUpper()); // 轉化為大寫,輸出"ABCD" Console.WriteLine(); //(6)填充對齊(PadLeft和PadRight) s = "ABCD"; Console.WriteLine(s.PadLeft(6, '_')); // 使用'_'填充字符串左部,使它擴充到6位總長度,輸出"__ABCD" Console.WriteLine(s.PadRight(6, '_')); // 使用'_'填充字符串右部,使它擴充到6位總長度,輸出"ABCD__" Console.WriteLine(); //(7)截頭去尾(Trim) s = "__AB__CD__"; Console.WriteLine(s.Trim('_')); // 移除字符串中頭部和尾部的'_'字符,輸出"AB__CD" Console.WriteLine(s.TrimStart('_')); // 移除字符串中頭部的'_'字符,輸出"AB__CD__" Console.WriteLine(s.TrimEnd('_')); // 移除字符串中尾部的'_'字符,輸出"__AB__CD" Console.WriteLine(); //(8)插入和刪除(Insert和Remove) s = "ADEF"; Console.WriteLine(s.Insert(1, "BC")); // 在字符串的第2位處插入字符串"BC",輸出"ABCDEF" Console.WriteLine(s); Console.WriteLine(s.Remove(1)); // 從字符串的第2位開始到最后的字符都刪除,輸出"A" Console.WriteLine(s); Console.WriteLine(s.Remove(0, 2)); // 從字符串的第1位開始刪除2個字符,輸出"EF" Console.WriteLine(); //(9)替換字符(串)(Replace) s = "A_B_C_D"; Console.WriteLine(s.Replace('_', '-')); // 把字符串中的'_'字符替換為'-',輸出"A-B-C-D" Console.WriteLine(s.Replace("_", "")); // 把字符串中的"_"替換為空字符串,輸出"A B C D" Console.WriteLine(); //(10)分割為字符串數組(Split)——互逆操作:聯合一個字符串靜態方法Join(seperator,arr[]) s = "AA,BB,CC,DD"; string[] arr1 = s.Split(','); // 以','字符對字符串進行分割,返回字符串數組 Console.WriteLine(arr1[0]); // 輸出"AA" Console.WriteLine(arr1[1]); // 輸出"BB" Console.WriteLine(arr1[2]); // 輸出"CC" Console.WriteLine(arr1[3]); // 輸出"DD" Console.WriteLine(); s = "AA--BB--CC--DD"; string[] arr2 = s.Replace("--", "-").Split('-'); // 以字符串進行分割的技巧:先把字符串"--"替換為單個字符"-",然后以'-'字符對字符串進行分割,返回字符串數組 Console.WriteLine(arr2[0]); // 輸出"AA" Console.WriteLine(arr2[1]); // 輸出"BB" Console.WriteLine(arr2[2]); // 輸出"CC" Console.WriteLine(arr2[3]); // 輸出"DD" Console.WriteLine(); //(11)格式化(靜態方法Format) Console.WriteLine(string.Format("{0} + {1} = {2}", 1, 2, 1 + 2)); Console.WriteLine(string.Format("{0} / {1} = {2:0.000}", 1, 3, 1.00 / 3.00)); Console.WriteLine(string.Format("{0:yyyy年MM月dd日}", DateTime.Now)); //(12)連接成一個字符串(靜態方法Concat、靜態方法Join和實例方法StringBuilder.Append) s = "A,B,C,D"; string[] arr3 = s.Split(','); // arr = {"A","B","C","D"} Console.WriteLine(string.Concat(arr3)); // 將一個字符串數組連接成一個字符串,輸出"ABCD" Console.WriteLine(string.Join(",", arr3)); // 以","作為分割符號將一個字符串數組連接成一個字符串,輸出"A,B,C,D" StringBuilder sb = new StringBuilder(); // 聲明一個字符串構造器實例 sb.Append("A"); // 使用字符串構造器連接字符串能獲得更高的性能 sb.Append('B'); Console.WriteLine(sb.ToString());// 輸出"AB"
11、Question:窗體控件較多時,重繪控件易引起窗體閃爍,重繪效率降低
Answer:通過使用控件的SuspendLayout()方法,可以將控件的布局暫時掛起,其后的代碼中將會把子控件的Layout事件暫時掛起,只是把相應屬性的值設置為新值,並不激發Layout事件,待調用ResumeLayout()方法后,再一起使子控件的Layout事件生效。當需要立即執行布局事件時,可以直接調用PerformLayout()方法。
在設置子控件的一些與外觀、布局有關的屬性時,比如Size、Location、Anchor或Dock等,會激發子控件的Control.Layout事件,並可能會引起窗口重繪。當子控件較多時,如果頻繁設置上述屬性(例如在窗體的初始化代碼中),多個子控件的Layout事件會引起窗口重繪效率問題,比如閃爍。特別地,通過動態加載插件生成的UI對象特別多時,閃爍的情況就特別嚴重。此時,我們就要考慮上述解決辦法。
12、Question:加密狗(SoftDog)的使用
Answer:程序啟動時先判斷加密狗的序列號,決定是否啟動程序;啟動后再通過定時器定期檢查加密狗的序列號,若發現錯誤及時退出程序。
13、Question:串口編程
Answer:SerialPort組件
14、Question:多線程中,跨線程訪問控件出錯
Answer:將訪問控件的代碼封裝成一個方法,再通過Invoke()調用其委托delegate。
15、Question:窗體全屏
Answer:代碼如下所示:
private void fullScreen() { this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; //this.WindowState = FormWindowState.Maximized; //屏幕分辨率 int nScreenWidth = Screen.PrimaryScreen.Bounds.Width; int nScreenHeight = Screen.PrimaryScreen.Bounds.Height; int nWidthBorder = (this.Width - this.ClientRectangle.Width) / 2; int nHeightTitle = this.Height - this.ClientRectangle.Height - nWidthBorder; this.Left = -nWidthBorder; this.Top = -nHeightTitle; this.Width = nScreenWidth + nWidthBorder * 2; this.Height = nScreenHeight + nHeightTitle + nWidthBorder; }
16、Question:焦點在其他控件上時,窗體接收不到按鍵消息
Answer:設置this.KeyPreview = true;(該值指示在將鍵事件傳遞到具有焦點的控件前,窗體是否將接收此鍵事件)
電梯多媒體相關鏈接:
ELCD_XXXM電梯多媒體顯示器:http://www.embedtools.com/ADPlayer/