發表文章

目前顯示的是 8月, 2018的文章

C# 取得 Windows 內所有程序視窗名稱、類別、指標

圖片
Get windows process handle / title name / class name 這篇其實是用來輔助 powerbuilder 寫的,因為大多數的第三方軟體都習慣會透過 FindWindow 這個API來確認己方程式是否已經啟動。 但是通常會不清楚自己開發工具開發的視窗會是哪種 Class Name ,所以利用下面簡單方式把電腦內所有程序的 handle / title name / class name 全部列出來查個清楚。 由於呼叫了 C 元件(COM API)所以需要多使用下面幾種 引用 using System.Runtime.InteropServices; using System.Text; using System.Collections; 程式的部分我將使用一個多行的 TextBox 把資訊列出來: namespace EnumWindows20 {     public partial class Form1 : Form     {         //Define Unmanaged API         public delegate bool EnumedWindow ( IntPtr handleWindow, ArrayList handles);         [ DllImport ( "user32.dll" , CharSet = CharSet.Auto, SetLastError = true)]         [return: MarshalAs(UnmanagedType.Bool)]         public static extern bool EnumWindows ( EnumedWindow lpEnumFunc, ArrayList lParam);         [ DllImport ( "user32.dll" , SetLastError = true, CharSet = CharSet.Auto)]         public static extern int GetClassName ( IntPtr hWnd, StringBuilder lpCl

C# HEX 字串 產生方式 (HEX KEY Gen)

很多時候,需要產生 HEX KEY 來做為唯一值,或是種子密碼來用,一般的情況我們會檢單的使用亂數(Random)來產生 Random rnd = new Random(); int num = rnd.Next(); string hexData = num.ToString("X"); 但是,許多人都知道,如果要產生很長的HEX字串,這個 Ramdom 是不夠力的。 而且也有『不夠亂』的問題存在(受限於Random演算法) 當然如果需要32字元的 HEX 字串,也可以直接使用 GUID 產生方式來獲得: string guidString = Guid.NewGuid().ToString().Replace("-", "").ToUpper(); string hexData = guidString; 但是如果要再更長,夠亂的HEX字串呢? 則可以使用 RNGCryptoServiceProvider 來處理 使用前記得引用 System.Security.Cryptography byte[] bytes = new byte[16]; using (var rng = new RNGCryptoServiceProvider()) {         rng.GetBytes(bytes); } string sBytes = BitConverter.ToString(bytes).Replace("-", ""); string hexData = sBytes; 長度的決定就由 byte 陣列大小來決定,因為一個byte可以生成2個字元的HEX碼, 所以byte[16]可以生成32字元HEX碼,byte[32]可以生成64字元的HEX碼,依此類推。

Microsoft Server 2008 / 2012 工作排程器 無法正常執行 C# [.NET] 程式

圖片
這個問題是我常常遇到的,很多時候寫Server端的程式通常是需要配合排程(工作排程器)執行的。 而這個工作排程器好似從2008以後的版本就跟2003有不少差異。 但就寫程式的工程師而言,有一個非常要注意的地方,那就是『程式執行位置』,底下演示一段程式碼來顯示 正常情況下 ,你的程式取得的程式所在位置資訊 我的程式位置在 D:\TEST 11\CnetAppPath string dir = System.Environment.CurrentDirectory; 位置: D:\TEST 11\CnetAppPath string dir = System.Windows.Forms.Application.StartupPath; 位置: D:\TEST 11\CnetAppPath string dir = System.IO.Directory.GetCurrentDirectory(); 位置: D:\TEST 11\CnetAppPath string dir = System.AppDomain.CurrentDomain.BaseDirectory; 位置: D:\TEST 11\CnetAppPath\ string dir = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; 位置: D:\TEST 11\CnetAppPath\ string dir = System.Windows.Forms.Application.ExecutablePath; 位置: D:\TEST 11\CnetAppPath\AppPath.exe string dir = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; 位置: D:\TEST 11\CnetAppPath\AppPath.exe string dir = this.GetType().Assembly.Location; 位置: D:\TEST 11\CnetAppPath\AppPath.exe 假設,我建立一個 捷徑 ,一般情況下捷徑裡面會有一個設定值『開始位置』

sybase 資料庫查詢 table ID 和 table name 對應

連入指定資料庫後,查詢指令 Select name , id , uid , sysstat From sysobjects Where type = 'U' 其他類型資料庫例如MS SQL,where好像用 xtype 來查: Select name , id From sysobjects Where xtype = 'U'

C# 偵測資料夾內檔案狀態是否被鎖定(或是可用)

參考來源: https://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use 因為常常會用到,所以先收集起來,註解改用中文 記得要 using System.IO; DirectoryInfo directoryInfo = new DirectoryInfo (sourcePath); foreach(FileInfo fi in directoryInfo.GetFiles()) {     if (!isFileLocked(fi) && fi.Length > 0)     {         // ...繼續處理可用檔案     } } 這個 isFileLocked 如下: protected virtual bool IsFileLocked(FileInfo file) {     FileStream stream = null;     try     {         stream = file.Open( FileMode .Open, FileAccess .Read, FileShare .None);     }     catch ( IOException )     {         //檔案無法開啟可能原因:         // 檔案仍然被寫入狀態         // 被其他Thread程序使用中         // 已經不存在 (或被程序處理掉了)         return true ;     }     finally     {         //如果已經被開啟不管狀態為何,記得要關閉資源         if (stream != null)             stream.Close();     }     //可以被開啟,回報檔案未被鎖定     return false ; }

電子發票 QR碼產生用程式碼 C# .NET

來源:財政部 註解:me 使用時注意 namespace using System; using System.IO; using System.Text; using System.Security.Cryptography; namespace tw.gov.nat.einvoice.qrutil {     class QREncrypter     {         /// <summary>         /// 將發票資訊文字加密成驗證文字         /// </summary>         /// <param name="plainText">發票資訊</param>         /// <param name="AESKey">種子密碼(QRcode)</param>         /// <returns>加密後的HEX字串</returns>         public string AESEncrypt( string plainText, string AESKey)         {             byte [] bytes = Encoding .Default.GetBytes(plainText);             ICryptoTransform transform = new RijndaelManaged             {                 KeySize = 0x80,                 Key = this.convertHexToByte(AESKey),                 BlockSize = 0x80,                 IV = Convert.FromBase64String("Dt8lyToo17X/XkXaQvihuA==")             }.CreateEncryptor();             MemoryStream stream = new MemoryStr

C# 如何產生不重複的隨機碼

某些情況下,需要產生一系列的亂碼,而且不重複。 下面兩種方式都可以達到效果 下面這個範例是打亂 1 - 9999 數字排序,然後取出前 1000 筆紀錄來使用。 方法一:傻瓜產生法 一般而言會使用迴圈,然後一邊產生亂碼一邊檢查是否重複。 Random rnd = new Random(); List<int> list1 = new List<int>(); do {     int number = rnd.Next(1, 9999);     int dup = list1.IndexOf(number);     if (dup < 0)     {         list1.Add(number);     } } while (list1.Count < 1000); 優點:速度快 缺點:當取號數量等於亂數數量時,可能會變成迴圈永遠不會結束(因為最後一碼超難取到)。 方法二:洗牌法 下面使用一種亂數排序方式,將一系列數字打亂其順序,然後再取出要使用的數字範圍,就可以很快的得到我們要的亂數範圍。 Random rnd = new Random(); List<int> randomList = Enumerable.Range(1, 9999)     .OrderBy(x => rnd.Next()).Take(1000).ToList(); 優點:直覺取號,當取號數量等於亂數數量時保證可取。 缺點:耗時稍多(其實頂多比方法一多十幾毫秒而已)。 夠簡單吧!

C# Base64 Encoding and Decoding

圖片
It make a record . using dotNet Framwork 4.5 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace base64dne {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();             cbEncoding.Sorted = true;         }         private void Form1_Load(object sender, EventArgs e)         {             //comboBox initial (Get Encoding list)             foreach (EncodingInfo ei in Encoding.GetEncodings())             {                 cbEncoding.Items.Add(ei.Name);                  }             cbEncoding.Text = Encoding.Default.BodyName;                   }         /// <summary>         /// Base64 Decoding         /// </summary>         /// <param name="sender"></param>      

C# string 裡面包含 \0 字元處理方式

圖片
很多時候我們會從檔案、裝置或是服務去讀取串流文字 ( Stream ),再放到畫面的 TextBox 顯示,但是有時候串流文字裡面包含了 "\0" 這樣的溢出字元 (escape character)。 這個 "\0" 溢出字元,會被 TextBox 當成字串終止符號,倒致顯示中斷,例如 下面程式顯示出來的結果: 因此,這個 "\0" 需要處理一下: 這樣就可以了。