VS2003 C# - 自訂函式庫 (My Class) 適用於 Borland User |
|
digitraveler
初階會員 發表:89 回覆:91 積分:46 註冊:2005-06-01 發送簡訊給我 |
使用 Borland RAD 開發工具 (Delphi / C++ Builder) 十幾年, 換到 C# 平台有許多不習慣 , 剛開始時連簡單的 ShowMessage() 功能都找不到 , 經過一段陣痛期後 , 總算慢慢搞定 , 不過要去記不同語言的函式名稱很累 , 而且 Delphi / C++ Builder 是公司仍在使用的開發工具 , 不能完全拋棄 , 所以想到何不把 C# 函式名稱包裝成跟 Delphi / C++ Builder 一樣 , 使用起來就順手多了
本函式 - Win32GlobalClass.cs , 已開發了快兩年 , 是陸陸續續補強的 , 不一一介紹內部包裝了哪些 Borland 函式 , 相信 Borland User 一看就知 , 我只能說歷經了兩年的補強 , 開發一般程式會用到的 Borland 函式都差不多齊了 , 不足的部份我再陸續補入 完整內容請見 http://tw.myblog.yahoo.com/bruce0211/article?mid=241&prev=-1&next=93 編輯記錄
|
syntax
尊榮會員 發表:26 回覆:1139 積分:1258 註冊:2002-04-23 發送簡訊給我 |
兩年,挖,你的毅力真強
像我都只能放本書在旁邊查 ===================引 用 digitraveler 文 章=================== 使用 Borland RAD 開發工具 (Delphi / C Builder) 十幾年, 換到 C# 平台有許多不習慣 , 剛開始時連簡單的 ShowMessage() 功能都找不到 , 經過一段陣痛期後 , 總算慢慢搞定 , 不過要去記不同語言的函式名稱很累 , 而且 Delphi / C Builder 是公司仍在使用的開發工具 , 不能完全拋棄 , 所以想到何不把 C# 函式名稱包裝成跟 Delphi / C Builder 一樣 , 使用起來就順手多了 本函式 - Win32GlobalClass.cs , 已開發了快兩年 , 是陸陸續續補強的 , 不一一介紹內部包裝了哪些 Borland 函式 , 相信 Borland User 一看就知 , 我只能說歷經了兩年的補強 , 開發一般程式會用到的 Borland 函式都差不多齊了 , 不足的部份我再陸續補入 完整內容請見 http://tw.myblog.yahoo.com/bruce0211/article?mid=241&prev=-1&next=93 [code c#] using System; using System.Runtime.InteropServices; using System.Text; using System.IO; using System.Windows.Forms; using System.Collections; //ArrayList using System.Drawing; //2008/12/17 using System.Drawing.Imaging; //2008/12/17 using System.Data; //2008/12/17 using System.Threading; //2009/03/10 //======================================================================================= //<修改歷程> // //2009/07/16 根據貓老大在我部落格留言所 Ansi string 相關處理修正 //2009/08/17 將螢幕及Form存檔格式由 png 改成 jpg 檔 (應用範圍較廣) // GetFileList() 增加可遞迴處理子目錄下的檔案 // 增加取目錄函式 GetDirList() // 增加目錄處理相關函式 DirMove() 目錄搬移, DirDelete() 目錄刪除, DirCopy() 目錄複製 //2009/09/03 替 TStringList 增加 Text 屬性 // 替 TStringList 增加 Strings[] 屬性 (原本是使用 Strings() 方法) // 替 TStringList 增加兩個方法 : Values() 及 SetValues() // ListBox.Text 屬性無法讀取(無反應), 故幫其建讀寫方法 : GetListBoxText() 及 SetListBoxText() // string 的 Replace 屬性不能用(無反應), 自己寫相關功能 ReplaceStr() //2009/09/10 加入 StrSegCount() 函式 //2009/09/30 替 TIniFile 加入 ReadSections(), ReadSection(), ReadSectionValues(), SectionExists() //======================================================================================= //<筆記篇> // //整數陣列宣告方式 int[] hour_value // hour_value = new int[24]; // //事件共用 //private void timer1_Tick(object sender, System.EventArgs e) //{ // button2_Click(sender,e); //} // //事件共用 例二 //private void button11_Click(object sender, System.EventArgs e) //{ // //不同 Tag 的 Button 呼叫相同的 Button_Click // MyKeyIdDown(Convert.ToInt32(((Button)sender).Tag)); //} //======================================================================================= public class My { //FindWindow() [DllImport("user32.dll")] public static extern int FindWindow(string strclassName, string strWindowName); //FindWindowEx() [DllImport("user32.dll",EntryPoint="FindWindowEx")] private static extern int FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); //SendMessage() [DllImport("User32.dll",EntryPoint="SendMessage")] private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam); //ShellExecute() 2008/11/21 [System.Runtime.InteropServices.DllImport("shell32.dll")] private static extern long ShellExecute(Int32 hWnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, long nShowCmd); //GUI 相關 2008/12/17 [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern IntPtr CreateDC(string lpDriverName, string lpDeviceName, string lpOutput, string lpInitData); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleDC(IntPtr hDC); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern int GetDeviceCaps(IntPtr hdc, int nIndex); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern int BitBlt(IntPtr desthDC, int srcX, int srcY, int srcW, int srcH, IntPtr srchDC, int destX, int destY, int op); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern int DeleteDC(IntPtr hDC); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern int DeleteObject(IntPtr hObj); //SystemParametersInfo() [DllImport("user32.dll",EntryPoint="SystemParametersInfoA")] private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); //自訂 ShowMessage() 函式 public static void ShowMessage(string bufstr) { System.Windows.Forms.MessageBox.Show(bufstr); } //取系統資訊相關 -------------------------------------------------- public static string ApplicationPath() { return System.Windows.Forms.Application.StartupPath; } public static string ApplicationName() { return System.Windows.Forms.Application.ExecutablePath; } public static string ApplicationIniName() { string tmp; tmp=System.Windows.Forms.Application.ExecutablePath; tmp=tmp.Substring(0,tmp.Length-4) ".ini"; return tmp; } public static string ApplicationLogName() { string tmp; tmp=System.Windows.Forms.Application.ExecutablePath; tmp=tmp.Substring(0,tmp.Length-4) ".log"; return tmp; } public static DateTime Date() { return DateTime.Now.Date; } public static DateTime Now() { return DateTime.Now; } public static string NowStr() { //加了 System.Globalization.DateTimeFormatInfo.InvariantInfo 才不會用民國 return DateTime.Now.ToString("yy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo); } public static string DateStr() { return DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo); } public static string TimeStr() { return DateTime.Now.ToString("HHmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo); } public static void Sleep(int ms) //會 hold 住 { Thread.Sleep(ms); } public static void Delay(int ms) //不會 hold 住 { int time = Environment.TickCount; while(true) { Application.DoEvents(); if(Environment.TickCount - time >= ms) break; } } //型態轉換相關 -------------------------------------------------- public static string IntToStr(int v) { return v.ToString(); } public static int StrToInt(string bufstr) { int r = 0; try { r = Convert.ToInt32(bufstr); //或 r = int32.Parse(bufstr); } catch (Exception ex) { //MessageBox.Show(ex.Message); //My.DebugLog("My.StrToInt() error : " ex.Message); r = 0; } return r; } public static string FormatDateTime(string format, DateTime d) { string f=""; string tmp, tmp2; for (int i=0; i<=format.Length-1; i ) { tmp=format.Substring(i,1); tmp2=tmp; if (tmp=="Y" || tmp=="y") tmp2="y"; if (tmp=="M" || tmp=="m") tmp2="M"; if (tmp=="D" || tmp=="d") tmp2="d"; if (tmp=="H" || tmp=="h") tmp2="H"; if (tmp=="N" || tmp=="n") tmp2="m"; if (tmp=="S" || tmp=="s") tmp2="s"; if (tmp=="Z" || tmp=="z") tmp2="f"; //2008/12/17 f=f tmp2; } //加了 System.Globalization.DateTimeFormatInfo.InvariantInfo 才不會用民國 return d.ToString(f,System.Globalization.DateTimeFormatInfo.InvariantInfo); } //Log 處理相關 -------------------------------------------------- //public static void DebugLog(string bufstr) //{ // if (g.debug_sw==1) SaveLog(" //} public static void SaveApLog(string bufstr) { StreamWriter sw = new StreamWriter(My.ApplicationLogName(), true, System.Text.Encoding.Default); sw.WriteLine(NowStr() " " bufstr); sw.Close(); } public static void SaveApDateLog(string bufstr) { string date_log_name=My.ApplicationPath() "\\" DateStr() ".log"; StreamWriter sw = new StreamWriter(date_log_name, true, System.Text.Encoding.Default); sw.WriteLine(NowStr() " " bufstr); sw.Close(); } //字串處理相關 -------------------------------------------------- public static int AnsiLength(string bufstr) { //return bufstr.Length; /* byte[] bytData = Encoding.Unicode.GetBytes(bufstr); string r = Encoding.Default.GetString(bytData); return r.Length; //用於 Ansi 字串(如 r)有問題 , 如取"大家好1" -> 7 , 如取"大家壞1" -> 6 */ string h=StrToAnsiHex(bufstr); return h.Length/2; } public static string AnsiSubString(string bufstr, int stridx, int len) { /* if (bufstr.Length==0) return ""; byte[] bytData = Encoding.Unicode.GetBytes(bufstr); string r1 = Encoding.Default.GetString(bytData); int len2=len; if (len2>(r1.Length-stridx 1)) len2=r1.Length-stridx 1; //MessageBox.Show(len2.ToString()); //這裡有問題 如取"大家好1" 之 (5,2) => "好" , 抓出值錯誤 //可見 .Substring() 用於 Ansi 字串(如 r1)會有問題 string r2 = r1.Substring(stridx-1,len2); //MessageBox.Show("r1='" r1 "' len=" r1.Length.ToString()); //MessageBox.Show("r2='" r2 "'"); //MessageBox.Show("r1='" StrToAnsiHex(r1) "'"); //MessageBox.Show("r2='" StrToAnsiHex(r2) "'"); byte[] bytData2 = Encoding.Default.GetBytes(r2); string r3 = Encoding.Unicode.GetString(bytData2); return r3; */ if (bufstr.Length==0) return ""; string h=StrToAnsiHex(bufstr); int len2=len; if (len2>((h.Length/2)-stridx 1)) len2=(h.Length/2)-stridx 1; string hh=h.Substring((stridx-1)*2,len2*2); return AnsiHexToStr(hh); } public static string StrToAnsiHex(string s) { //"大家好1" => ansi="A46AAE61A66E31"; unicode="2759B65B7D59310" //"大家好" => ansi="A46AAE61A66E" ; unicode="2759B65B7D59" byte[] byteData = Encoding.Default.GetBytes(s); string r=""; for (int i=0; i //--------------------------------------------------------------------------- public static string Trim(string bufstr) { string r=""; try { r=bufstr.Trim(); } catch { ;; } return r; } //--------------------------------------------------------------------------- public static int Length(string bufstr) { //remark on 2009/07/16 //return AnsiLength(bufstr); //2009/07/16 根據貓老大在我部落格留言所修正 byte[] bytData = Encoding.GetEncoding(950).GetBytes(bufstr); int r=bytData.Length; return r; } //--------------------------------------------------------------------------- public static string SubString(string bufstr, int stridx, int len) //stridx 從 1 起算 { //remark on 2009/07/16 //return AnsiSubString(bufstr, stridx, len); //2009/07/16 根據貓老大在我部落格留言所修正 byte[] bytData = Encoding.GetEncoding(950).GetBytes(bufstr); int fix_len=len; int fix_stridx=stridx; if (fix_stridx<1) fix_stridx=1; string r=""; if (fix_stridx>Length(bufstr)) return r; if ((fix_stridx len-1)>Length(bufstr)) { fix_len=Length(bufstr)-fix_stridx 1; } r = Encoding.GetEncoding(950).GetString(bytData, fix_stridx-1, fix_len); return r; } //--------------------------------------------------------------------------- public static string Copy(string bufstr, int stridx, int len) { //remark on 2009/07/16 //return AnsiSubString(bufstr, stridx, len); //2009/07/16 根據貓老大在我部落格留言所修正 return SubString(bufstr, stridx, len); } //--------------------------------------------------------------------------- public static string Left(string bufstr, int len) { /* if (bufstr.Length==0) return ""; if (len>bufstr.Length) return bufstr; return bufstr.Substring(0,len); */ //remark on 2009/07/16 //return AnsiSubString(bufstr, 1, len); //2009/07/16 根據貓老大在我部落格留言所修正 return SubString(bufstr, 1, len); } //--------------------------------------------------------------------------- public static string Right(string bufstr, int len) { /* if (bufstr.Length==0) return ""; if (len>bufstr.Length) return bufstr; if (bufstr.Length string[] tmp = bufstr.Split(bufkey); //return tmp[idx]; return tmp[idx-1]; //2007/12/05 } //--------------------------------------------------------------------------- public static int StrSegCount(string bufstr, char bufkey) //2009/09/10 { string[] tmp = bufstr.Split(bufkey); return tmp.Length; } //--------------------------------------------------------------------------- public static string RepeatStr(string bufstr, int num) //2007/06/17 { string r = ""; for (int i=1; i<=num; i ) { r = r bufstr; } return r; } //--------------------------------------------------------------------------- public static string FormatFloat(string format, int num) //2007/07/03 { string r = num.ToString(); if (r.Length return r; */ String r=""; switch(Align) { case 0 : r=Str; if (AnsiLength(r)>=Alength) r=Left(r,Alength); else r=r Space(Alength-AnsiLength(r)); break; case -1 : //左靠 r=Trim(Str); if (AnsiLength(r)>=Alength) r=Left(r,Alength); else r=r Space(Alength-AnsiLength(r)); break; case 1 : //右靠 r=Trim(Str); if (AnsiLength(r)>=Alength) r=Right(r,Alength); else r=Space(Alength-AnsiLength(r)) r; break; } return r; } //--------------------------------------------------------------------------- public static string Space(int n) //重複 n 個空白 { String r=""; for (int i=1; i<=n ; i ) { r = r " "; } return r; } //--------------------------------------------------------------------------- //2009/09/03 string 的 Replace 屬性不能用, 自己寫相關功能 public static string ReplaceStr(string str, string old_value, string new_value) { string r=""; string comp_str=""; string str_fix=str; string tail; /* //去除最尾端 "\r\n" while (true) { if (str_fix=="") break; if (str_fix.EndsWith("\r") || str_fix.EndsWith("\n")) { //str_fix=str_fix.Remove(Length(str_fix)-1,1); //Remove 可能有 unicode 的問題 str_fix=CutRight(str_fix,1); } else break; } */ //for (int i=1; i<=(Length(str_fix)-Length(old_value) 1); i ) //尾端不用比 for (int i=1; i<=Length(str_fix); i ) //尾端不用比但還是要一個個加到 r 中, 所以要全跑完 { comp_str=SubString(str_fix,i,Length(old_value)); if (comp_str.CompareTo(old_value)==0) { r=r new_value; i=i Length(old_value)-1; continue; } else { r=r SubString(str_fix,i,1); } } return r; } //檔案目錄 相關 -------------------------------------------------- public static void FileMove(string fn1, string fn2) { if (File.Exists(fn1)) { if (File.Exists(fn2)) { File.Delete(fn2); } File.Move(fn1, fn2); } } public static void FileCopy(string fn1, string fn2) { if (File.Exists(fn1)) { if (File.Exists(fn2)) { File.Delete(fn2); } File.Copy(fn1, fn2); } } public static void FileDelete(string fn) { if (File.Exists(fn)) File.Delete(fn); } public static void DeleteFile(string fn) { if (File.Exists(fn)) File.Delete(fn); } public static bool FileExists(string fn) { return File.Exists(fn); } public static string ExtractFileName(string fn) { string r=""; //if (File.Exists(fn)) //mark on 2007/12/10 r = Path.GetFileName(fn); return r; } public static string ExtractFilePath(string fn) //2007/12/10 { string r=""; r = Path.GetDirectoryName(fn); return r; } public static DateTime FileDate(string fn) //2008/11/21 { return File.GetLastWriteTime(fn); } //2009/08/17 由 DirectoryExists() 改成 DirExists() public static bool DirExists(string bufstr) { return System.IO.Directory.Exists(bufstr); } //2009/08/17 由 CreateDirectory() 改成 CreateDir() public static void CreateDir(string bufstr) { if (!(System.IO.Directory.Exists(bufstr))) { System.IO.Directory.CreateDirectory(bufstr); } } //2009/08/17 相似函式 public static void DirCreate(string bufstr) { CreateDir(bufstr); } //2009/08/17 目錄搬移(含子目錄) //例 : My.DirMove("c:\\REEL_20090711","c:\\REEL_20090711_2"); public static void DirMove(string sur_dir, string dest_dir) { if ((System.IO.Directory.Exists(sur_dir))) { Directory.Move(sur_dir, dest_dir); } } //2009/08/17 目錄刪除(含子目錄) //例 : My.DirDelete("C:\\REEL_20090711_2"); public static void DirDelete(string sur_dir) { /* 這樣只能刪除空目錄 if ((System.IO.Directory.Exists(sur_dir))) { Directory.Delete(sur_dir); } */ if (!(System.IO.Directory.Exists(sur_dir))) return; string sdir=sur_dir; if (Right(sdir,1)!="\\") sdir=sdir "\\"; TStringList TmpList = new TStringList(); //清空所有檔案 GetFileList(ref TmpList, sdir "*.*/s"); for (int i=0; i<=TmpList.Count-1; i ) { File.Delete(TmpList.Strings(i)); } //清空所有目錄 //MessageBox.Show(sdir "/s"); GetDirList(ref TmpList, sdir "/s"); TmpList.Sort(); for (int i=TmpList.Count-1; i>=0; i--) //目錄要從後往前砍,不然會砍不掉 { Directory.Delete(TmpList.Strings(i)); } Directory.Delete(sur_dir); } //2009/08/17 目錄複製(含子目錄) //例 : My.DirCopy("c:\\REEL_20090711","c:\\REEL_20090711_2"); public static void DirCopy(string sur_dir, string dest_dir) { if (!(System.IO.Directory.Exists(sur_dir))) return; string sdir=sur_dir; string ddir=dest_dir; if (Right(sdir,1)=="\\") sdir=CutRight(sdir,1); if (Right(ddir,1)=="\\") ddir=CutRight(ddir,1); //建立目的目錄失敗的話... try { Directory.CreateDirectory(ddir); } catch (Exception ex) { return; } TStringList TmpList = new TStringList(); //取得並複製所有目錄名(含空目錄) GetDirList(ref TmpList, sdir "/s"); TmpList.Sort(); string tmp,tmp2; for (int i=0; i<=TmpList.Count-1; i ) { tmp=TmpList.Strings(i); tmp=CutLeft(tmp,Length(sdir)); tmp2=ddir tmp; CreateDir(tmp2); } //取得並複製所有檔案 GetFileList(ref TmpList, sdir "\\*.*/s"); TmpList.Sort(); for (int i=0; i<=TmpList.Count-1; i ) { tmp=TmpList.Strings(i); tmp=CutLeft(tmp,Length(sdir)); tmp2=ddir tmp; //MessageBox.Show("FileCopy(" TmpList.Strings(i) "," tmp2 ")"); try { FileCopy(TmpList.Strings(i), tmp2); } catch (Exception ex) { MessageBox.Show("錯誤 : FileCopy(" TmpList.Strings(i) "," tmp2 ")"); } } } //2009/08/17 相似函式 public static void XCopy(string sur_dir, string dest_dir) { DirCopy(sur_dir, dest_dir); } //2008/08/22 ----------------------------------------------------------- //<例> //1.My.GetFileList(ref listBox1, My.ApplicationPath() "pre*.txt"); //2.My.GetFileList(ref listBox1, "c:\\REEL_20090711\\*.*"); //3.My.GetFileList(ref listBox1, "c:\\REEL_20090711\\*.*/s"); //---------------------------------------------------------------------- public static void GetFileList(ref ListBox tmp_listbox, string AFindFile) //2007/12/10 { string find_path, find_file; find_path=ExtractFilePath(AFindFile); find_file=ExtractFileName(AFindFile); //2009/08/17 bool with_sub_dir=false; if (Right(AFindFile,2)=="/s" || Right(AFindFile,2)=="/S") { find_file=CutRight(AFindFile,2); find_path=ExtractFilePath(find_file); find_file=ExtractFileName(find_file); with_sub_dir=true; } tmp_listbox.Items.Clear(); if (!DirExists(find_path)) { return; } foreach (string f in Directory.GetFiles(find_path, find_file)) { tmp_listbox.Items.Add(f); } //2009/08/17 遞迴處理子目錄 if (with_sub_dir) { foreach (string f in Directory.GetDirectories(find_path)) { TStringList TmpList = new TStringList(); GetFileList(ref TmpList, f "\\" find_file "/s"); for (int i=0; i<=TmpList.Count-1; i ) { tmp_listbox.Items.Add(TmpList.Strings(i)); } } } } public static void GetFileList(ref TStringList tmp_listbox, string AFindFile) //2007/12/10 { string find_path, find_file; find_path=ExtractFilePath(AFindFile); find_file=ExtractFileName(AFindFile); //2009/08/17 bool with_sub_dir=false; if (Right(AFindFile,2)=="/s" || Right(AFindFile,2)=="/S") { find_file=CutRight(AFindFile,2); find_path=ExtractFilePath(find_file); find_file=ExtractFileName(find_file); with_sub_dir=true; } tmp_listbox.Clear(); if (!DirExists(find_path)) { return; } foreach (string f in Directory.GetFiles(find_path, find_file)) { tmp_listbox.Add(f); } tmp_listbox.Sort(); //2009/08/17 遞迴處理子目錄 if (with_sub_dir) { foreach (string f in Directory.GetDirectories(find_path)) { TStringList TmpList = new TStringList(); GetFileList(ref TmpList, f "\\" find_file "/s"); tmp_listbox.AddRange(TmpList); } } } //2009/08/17 //My.GetDirList(ref listBox1, "c:\\REEL_20090711"); //My.GetDirList(ref listBox1, "c:\\REEL_20090711/s"); public static void GetDirList(ref ListBox tmp_listbox, string AFindDir) { string find_path; find_path=AFindDir; bool with_sub_dir=false; if (Right(AFindDir,2)=="/s" || Right(AFindDir,2)=="/S") { find_path=CutRight(AFindDir,2); with_sub_dir=true; } tmp_listbox.Items.Clear(); if (!DirExists(find_path)) { return; } foreach (string f in Directory.GetDirectories(find_path)) { tmp_listbox.Items.Add(f); } //遞迴處理子目錄 if (with_sub_dir) { foreach (string f in Directory.GetDirectories(find_path)) { TStringList TmpList = new TStringList(); GetDirList(ref TmpList, f "/s"); for (int i=0; i<=TmpList.Count-1; i ) { tmp_listbox.Items.Add(TmpList.Strings(i)); } } } tmp_listbox.Sorted=true; } //2009/08/17 //My.GetDirList(ref TmpList, "c:\\REEL_20090711"); //My.GetDirList(ref TmpList, "c:\\REEL_20090711/s"); public static void GetDirList(ref TStringList tmp_listbox, string AFindDir) { string find_path; find_path=AFindDir; bool with_sub_dir=false; if (Right(AFindDir,2)=="/s" || Right(AFindDir,2)=="/S") { find_path=CutRight(AFindDir,2); with_sub_dir=true; } tmp_listbox.Clear(); if (!DirExists(find_path)) { return; } foreach (string f in Directory.GetDirectories(find_path)) { tmp_listbox.Add(f); } tmp_listbox.Sort(); //遞迴處理子目錄 if (with_sub_dir) { foreach (string f in Directory.GetDirectories(find_path)) { TStringList TmpList = new TStringList(); GetDirList(ref TmpList, f "/s"); tmp_listbox.AddRange(TmpList); } } } //2009/09/03 ListBox.Text 屬性無法讀寫(無反應), 故幫其建讀取 Function public static string GetListBoxText(ListBox tmp_listbox) { string temp=""; foreach(string s in tmp_listbox.Items) temp=temp s "\r\n"; return temp; } //2009/09/03 ListBox.Text 屬性無法讀寫(無反應), 故幫其建讀取 Function public static void SetListBoxText(ref ListBox tmp_listbox, string sval) { string[] sArray=sval.Split('\n'); string temp=""; tmp_listbox.Items.Clear(); foreach(string s in sArray) { if (!s.EndsWith("\r")) tmp_listbox.Items.Add(s); else //tmp_listbox.Items.Add(s.Remove(Length(s)-1,1)); //Remove 可能有 unicode 的問題 tmp_listbox.Items.Add(CutRight(s,1)); } } /* 排序範例 private void Reverse(FileListBox list) { object[] tmp = new object[list.Items.Count]; (list.Items as ICollection).CopyTo(tmp, 0); if(list.Sorted) { Array.Reverse(tmp); } else { Array.Sort(tmp, new ReverseComparer(list)); } list.Items.Clear(); list.Items.AddRange(tmp); } private class ReverseComparer : System.Collections.IComparer { ListControl _list; public ReverseComparer(ListControl list) { _list = list; } #region IComparer Members public int Compare(object x, object y) { if (x == null) { if (y == null) { return 0; } return 1; } if (y == null) { return -1; } string xItemText = _list.GetItemText(x); string yItemText = _list.GetItemText(y); return -Application.CurrentCulture.CompareInfo.Compare(xItemText, yItemText, CompareOptions.StringSort); } #endregion } */ //呼叫外部程式 相關 -------------------------------------------------- public static void OpenFile(string fn) //以檔案所屬的工具開啟, 如 1.doc 用 MS WORD 開啟 { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = fn; proc.StartInfo.UseShellExecute = true; proc.Start(); } public static void NotePad(string fn) //以 notepad.exe 開啟檔案 { //[System.Runtime.InteropServices.DllImport("shell32.dll")] //private static extern long ShellExecute(Int32 hWnd, string lpOperation, //string lpFile, string lpParameters, string lpDirectory, long nShowCmd); const long SW_HIDE=0; const long SW_SHOWNORMAL=1; const long SW_SHOW=5; const long SW_RESTORE=9; const long SW_SHOWDEFAULT=10; ShellExecute(0, null, "notepad.exe", fn, null, SW_SHOW); } public static void UrlLink(string url) //2009/04/08 { //[System.Runtime.InteropServices.DllImport("shell32.dll")] //private static extern long ShellExecute(Int32 hWnd, string lpOperation, //string lpFile, string lpParameters, string lpDirectory, long nShowCmd); const long SW_HIDE=0; const long SW_SHOWNORMAL=1; const long SW_SHOW=5; const long SW_RESTORE=9; const long SW_SHOWDEFAULT=10; ShellExecute(0, null, url, null, null, SW_SHOWNORMAL); } //GUI 處理相關 2008/12/17 -------------------------------------------------- /* 使用範例 Bitmap bitmap; bitmap=My.CaptureControl(button1.CreateGraphics().GetHdc(),button1.Width,button1.Height); bitmap.Save(@"c:\1.png"); bitmap=My.CaptureScreen(); bitmap.Save(@"c:\2.png"); 或存成 jpg bitmap=My.CaptureControl(this.CreateGraphics().GetHdc(), this.Width, this.Height); bitmap.Save("c:\\1.jpg",ImageFormat.Jpeg); //using System.Drawing.Imaging 才認得 ImageFormat.Jpeg; bitmap=My.CaptureScreen(); bitmap.Save("c:\\2.jpg",ImageFormat.Jpeg); */ //將元件存成 png 檔 //例 //Bitmap bitmap; //bitmap=My.CaptureControl(button1.CreateGraphics().GetHdc(), button1.Width, button1.Height); //bitmap.Save(@"c:\1.png"); static public Bitmap CaptureControl(IntPtr SourceDC,int SourceWidth,int SourceHeight) { return Capture(SourceDC,SourceWidth,SourceHeight); } static public Bitmap CaptureScreen() { IntPtr screen=CreateDC("DISPLAY", "", "", ""); int sourceWidth=GetDeviceCaps(screen, 8); int sourceHeight=GetDeviceCaps(screen, 10); Capture(screen,sourceWidth,sourceHeight); Bitmap ret=Capture(screen,sourceWidth,sourceHeight); DeleteDC(screen); return ret; } static private Bitmap Capture(IntPtr SourceDC,int SourceWidth,int SourceHeight) { IntPtr destDC; IntPtr BMP, BMPOld; destDC = CreateCompatibleDC(SourceDC); BMP = CreateCompatibleBitmap(SourceDC, SourceWidth, SourceHeight); BMPOld = SelectObject(destDC, BMP); BitBlt(destDC, 0, 0, SourceWidth, SourceHeight, SourceDC, 0, 0, 13369376); BMP = SelectObject(destDC, BMPOld); DeleteDC(destDC); Bitmap ret = Image.FromHbitmap(BMP); DeleteObject(BMP); return ret; } //2008/12/17 將螢幕存成 png 檔 //2009/08/17 將螢幕存成 jpg 檔 (應用範圍較廣) //例 My.ScreenSaveToFile(""); public static void ScreenSaveToFile(string AFileName) { Bitmap bitmap; string my_filename; my_filename=Trim(AFileName); if (my_filename=="") { //my_filename="c:\\" FormatDateTime("mmdd_hhnnss_zzz",Now()) ".png"; //流水號檔名 //2009/08/17 my_filename="c:\\" FormatDateTime("mmdd_hhnnss_zzz",Now()) ".jpg"; //流水號檔名 } bitmap=CaptureScreen(); //bitmap.Save(my_filename); bitmap.Save(my_filename,ImageFormat.Jpeg); //2009/08/17 } //2008/12/17 將 Form 存成 png 檔 //2009/08/17 將 Form 存成 jpg 檔 (應用範圍較廣) //例 My.FormSaveToFile(this,""); public static void FormSaveToFile(Form AForm, string AFileName) { Bitmap bitmap; string my_filename; my_filename=Trim(AFileName); if (my_filename=="") { //my_filename="c:\\" FormatDateTime("mmdd_hhnnss_zzz",Now()) ".png"; //流水號檔名 //2009/08/17 my_filename="c:\\" FormatDateTime("mmdd_hhnnss_zzz",Now()) ".jpg"; //流水號檔名 } bitmap=CaptureForm(AForm.CreateGraphics().GetHdc(), AForm.Width, AForm.Height); //bitmap.Save(my_filename); bitmap.Save(my_filename,ImageFormat.Jpeg); //2009/08/17 } //存 Form 專用副程序 static private Bitmap CaptureForm(IntPtr SourceDC,int SourceWidth,int SourceHeight) { IntPtr destDC; IntPtr BMP, BMPOld; destDC = CreateCompatibleDC(SourceDC); BMP = CreateCompatibleBitmap(SourceDC, SourceWidth, SourceHeight); BMPOld = SelectObject(destDC, BMP); BitBlt(destDC, 0, 0, SourceWidth, SourceHeight, SourceDC, -4, -23, 13369376); BMP = SelectObject(destDC, BMPOld); DeleteDC(destDC); Bitmap ret = Image.FromHbitmap(BMP); DeleteObject(BMP); return ret; } //2008/12/17 更換螢幕桌布(一定要用 bmp 檔) //例 My.ScreenLoadFromFile("c:\\bg.bmp"); public static void ScreenLoadFromFile(string AFileName) { if (!FileExists(AFileName)) return; int SPI_SETDESKWALLPAPER = 20; int SPIF_SENDCHANGE = 0; SystemParametersInfo(20, 1, AFileName, 0x1 | 0x2 ); } } //======================================================================================= //範例 : TIniFile MyIni = new TIniFile(My.ApplicationIniName()); public class TIniFile { private string fileName; [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string fileName); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string fileName); //2009/09/30 加入 [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key,string def,byte[] retVal, int size,string fileName); //kernel32 中有 GetPrivateProfileInt() 但無 WritePrivateProfileInt() [DllImport("kernel32")] private static extern int GetPrivateProfileInt(string section, string key, int def, string fileName); public TIniFile(string INIPath) { fileName = INIPath; } ~TIniFile() { ;; } public void WriteString(string Section,string Key,string Value) { WritePrivateProfileString(Section,Key,Value,fileName); } public string ReadString(string Section,string Key, string def) { StringBuilder temp = new StringBuilder(1024); //2009/09/30 由 255 改成 1024 int i = GetPrivateProfileString(Section,Key,def,temp, 1024, fileName); return temp.ToString(); } public void WriteInt(string Section, string Key, int Value) { WritePrivateProfileString(Section, Key, Value.ToString(), fileName); } public int ReadInt(string Section, string Key, int def) { int i = GetPrivateProfileInt(Section, Key, def, fileName); return i; } //2008/11/08 public void WriteBool(string Section, string Key, bool Value) { int Value2; if (Value) Value2=1; else Value2=0; WritePrivateProfileString(Section, Key, Value2.ToString(), fileName); } //2008/11/08 public bool ReadBool(string Section, string Key, bool def) { int def2; if (def) def2=1 ; else def2=0; int i = GetPrivateProfileInt(Section, Key, def2, fileName); if (i==1) return true; else return false; } public void DeleteKey(string section, string key) { WritePrivateProfileString(section, key, null, fileName); } public void EraseSection(string section) { WritePrivateProfileString(section, null, null, fileName); } //2009/09/30 public void ReadSection(string section, ref ListBox tmp_listbox) { TStringList TmpList = new TStringList(); ReadSectionKeys(section, ref TmpList); tmp_listbox.Items.Clear(); for (int i=0; i<=TmpList.Count-1; i ) { tmp_listbox.Items.Add(TmpList.Strings(i)); } } //2009/09/30 public void ReadSection(string section, ref TStringList tmp_listbox) { TStringList TmpList = new TStringList(); ReadSectionKeys(section, ref TmpList); tmp_listbox.Clear(); for (int i=0; i<=TmpList.Count-1; i ) { tmp_listbox.Add(TmpList.Strings(i)); } } //2009/09/30 public void ReadSectionValues(string section, ref ListBox tmp_listbox) { TStringList TmpList = new TStringList(); ReadSectionKeys(section, ref TmpList); tmp_listbox.Items.Clear(); for (int i=0; i<=TmpList.Count-1; i ) { tmp_listbox.Items.Add(TmpList.Strings(i) "=" this.ReadString(section, TmpList.Strings(i), "")); } } //2009/09/30 public void ReadSectionValues(string section, ref TStringList tmp_listbox) { TStringList TmpList = new TStringList(); ReadSectionKeys(section, ref TmpList); tmp_listbox.Clear(); for (int i=0; i<=TmpList.Count-1; i ) { tmp_listbox.Add(TmpList.Strings(i) "=" this.ReadString(section, TmpList.Strings(i), "")); } } //2009/09/30 取得所有 Section 列表 public void ReadSections(ref ListBox tmp_listbox) { tmp_listbox.Items.Clear(); byte[] byteBuffer = new byte[65535]; string tmpStr = null; if (GetPrivateProfileString(null, null, null, byteBuffer, 65535, fileName) > 0) { foreach(byte abyte in byteBuffer) { if (abyte == 0) { if (tmpStr == null) { break; } else { tmp_listbox.Items.Add(tmpStr); tmpStr = null; } } else { tmpStr = tmpStr Convert.ToChar(abyte); } } } } //2009/09/30 public void ReadSections(ref TStringList tmp_listbox) { tmp_listbox.Clear(); byte[] byteBuffer = new byte[65535]; string tmpStr = null; if (GetPrivateProfileString(null, null, null, byteBuffer, 65535, fileName) > 0) { foreach(byte abyte in byteBuffer) { if (abyte == 0) { if (tmpStr == null) { break; } else { tmp_listbox.Add(tmpStr); tmpStr = null; } } else { tmpStr = tmpStr Convert.ToChar(abyte); } } } } //2009/09/30 public bool SectionExists(string section) { bool r=false; TStringList TmpList = new TStringList(); this.ReadSections(ref TmpList); string comp1=(section.ToUpper()).Trim(); string comp2; foreach(string tmp in TmpList) { comp2=(tmp.ToUpper()).Trim(); if (comp1.CompareTo(comp2)==0) { r=true; break; } } return r; } //2009/09/30 取得所有 Section 中 Key 列表 (VCL 無此函式) public void ReadSectionKeys(string section, ref TStringList tmp_listbox) { tmp_listbox.Clear(); byte[] byteBuffer = new byte[65535]; string tmpStr = null; if (GetPrivateProfileString(section, null, null, byteBuffer, 65535, fileName) > 0) { foreach(byte abyte in byteBuffer) { if (abyte == 0) { if (tmpStr == null) { break; } else { tmp_listbox.Add(tmpStr); tmpStr = null; } } else { tmpStr = tmpStr Convert.ToChar(abyte); } } } } } //======================================================================================= //------------------------------------------------- //TStringList //------------------------------------------------- //使用例 //TStringList TmpList = new TStringList(); //TmpList.Add("123"); //TmpList.Add("456"); //TmpList.SaveToFile("test.txt"); // //TmpList.LoadFromFile("test.txt"); //for (int i=0; i<=TmpList.Count-1; i ) //{ // //MessageBox.Show(TmpList[i]); // MessageBox.Show(TmpList.Strings(i)); //} //------------------------------------------------- public class TStringList : ArrayList { public void SaveToFile(string fn) { //StreamWriter sw = File.CreateText(fn); StreamWriter sw = new StreamWriter(fn, false, System.Text.Encoding.Default); //這樣才能寫出中文字元 for(int i = 0; i != this.Count; i ) { sw.WriteLine(this[i]); } sw.Close(); } public void LoadFromFile(string fn) { /* using (StreamReader sr = new StreamReader("TestFile.txt")) { string line; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } */ this.Clear(); /* StreamReader sr = new StreamReader(File.OpenRead(fn)); //或 StreamReader sr = new StreamReader(File.Open(fn, FileMode.Open)); */ //這樣才能讀入中文字元 StreamReader sr = new StreamReader(fn, System.Text.Encoding.Default); //或 System.Text.Encoding.Default while (sr.Peek() >= 0) { this.Add(sr.ReadLine()); } sr.Close(); } //2008/11/08 透過 Strings() 方法 public string Strings(int idx) { return this[idx].ToString(); } /* 有機會再開放使用 (因很多舊程式已習慣透過 Strings() 方法) //2009/09/03 改透過 Strings[] 屬性 public ArrayList Strings { get { return this; } set { object r= (object)Strings; r=value; } } */ //2009/09/03 public string Text { get { string temp=""; foreach(string s in this) temp=temp s "\r\n"; return temp; } set { string[] sArray=value.Split('\n'); string temp=""; this.Clear(); foreach(string s in sArray) { if (!s.EndsWith("\r")) this.Add(s); else //this.Add(s.Remove(s.Length-1,1)); //Remove 可能有 unicode 的問題 this.Add(My.CutRight(s,1)); } } } //2009/09/03 不曉得如何製造像 VCL 使用 Values["ID名稱"] 一樣的屬性 //所以只好透過兩個方法 , 讀:Values() 寫:SetValues() public string Values(string id) { string r=""; string tmp1,tmp2; foreach(string s in this) { tmp1=id.Trim().ToUpper(); tmp2=My.StrSeg(s,',',1); tmp2=tmp2.Trim().ToUpper(); if (tmp1==tmp2) { r=My.StrSeg(s,',',2); break; } } return r; } //2009/09/03 public void SetValues(string id, string sval) { string tmp1,tmp2; bool find_flag=false; for(int i = 0; i <= this.Count; i ) { tmp1=id.Trim().ToUpper(); tmp2=My.StrSeg(this[i].ToString(),',',1); tmp2=tmp2.Trim().ToUpper(); if (tmp1==tmp2) { this[i]=My.StrSeg(this[i].ToString(),',',1) "=" sval; find_flag=true; break; } } if (find_flag==false) this.Add(id "=" sval); } } //======================================================================================= public abstract class OneInstance //防止程式重複執行 { public static bool IsFirst(string appId) { bool ret=false; if(OpenMutex(0x1F0001,0,appId)==IntPtr.Zero) { CreateMutex(IntPtr.Zero,0,appId); ret=true; } return ret; } [DllImport("Kernel32.dll",CharSet=CharSet.Auto)] private static extern IntPtr OpenMutex( uint dwDesiredAccess, // access int bInheritHandle, // inheritance option string lpName // object name ); [DllImport("Kernel32.dll",CharSet=CharSet.Auto)] private static extern IntPtr CreateMutex( IntPtr lpMutexAttributes, // SD int bInitialOwner, // initial owner string lpName // object name ); } /* namespace WindowsApplication1 { /// /// Summary description for Class1. /// public class Class1 { public Class1() { // // TODO: Add constructor logic here // } } } */ [/code] |
digitraveler
初階會員 發表:89 回覆:91 積分:46 註冊:2005-06-01 發送簡訊給我 |
像是常用的把日期換字串, C# 的格式字串很複雜 , 如 大寫 M 代表月 , 小寫 m 代表分 , 誰記得住 ? , 日期還會雞婆的使用作業系統語言的國家紀元方式 , 要使用西元年 , 每次還要加入又臭又長的 System.Globalization.DateTimeFormatInfo.InvariantInfo 參數 ...
還不如直接包裝成跟 Borland 的 FormatDateTime(() 一樣的函式 , 使用上來的順手 [code c#] public static string FormatDateTime(string format, DateTime d) { string f=""; string tmp, tmp2; for (int i=0; i<=format.Length-1; i ) { tmp=format.Substring(i,1); tmp2=tmp; if (tmp=="Y" || tmp=="y") tmp2="y"; if (tmp=="M" || tmp=="m") tmp2="M"; if (tmp=="D" || tmp=="d") tmp2="d"; if (tmp=="H" || tmp=="h") tmp2="H"; if (tmp=="N" || tmp=="n") tmp2="m"; if (tmp=="S" || tmp=="s") tmp2="s"; if (tmp=="Z" || tmp=="z") tmp2="f"; //2008/12/17 f=f tmp2; } //加了 System.Globalization.DateTimeFormatInfo.InvariantInfo 才不會用民國 return d.ToString(f,System.Globalization.DateTimeFormatInfo.InvariantInfo); } [/code] |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |