2022年10月17日 星期一

[C#]語法混合應用

一些C# 的基礎應用範例

 int iData = 123;
string str = $"Hello{iData}!!";

Action<string> greet = name =>
{
    string greeting = $"hello {name}!";
    Console.WriteLine(greeting);
};
greet("world");



其他執行續範例說明:
正常寫法如以下兩段:
private void setText(Object str) { using (StreamWriter sw = new StreamWriter(@"D:\test.txt",true,Encoding.UTF8)) { sw.WriteLine(str.ToString()); } } protected void Button1_Click(object sender, EventArgs e) { string str = "測試四"; ThreadPool.QueueUserWorkItem(new WaitCallback(setText),(Object) str); }

透握委派方式簡化程式碼:
protected void Button1_Click(object sender, EventArgs e) { string str = "測試三"; ThreadPool.QueueUserWorkItem(delegate { using (StreamWriter sw = new StreamWriter(@"D:\test.txt", true, Encoding.UTF8)); //路徑 , 不複寫檔案 , 編碼 { sw.WriteLine(str); } }); }

透過Lambda寫法:
protected void Button1_Click(object sender, EventArgs e) { string str = "測試五"; ThreadPool.QueueUserWorkItem(callback => { using (StreamWriter sw = new StreamWriter(@"D:\test.txt", true, Encoding.UTF8)) { sw.WriteLine(str.ToString()); } }); }




參考來源:
https://learn.microsoft.com/zh-tw/dotnet/csharp/language-reference/operators/lambda-expressions
https://dotblogs.com.tw/ken74114/2010/12/08/19988

2022年10月14日 星期五

[C#]圖形比對

public static bool ImageCompareString(Bitmap firstImage, Bitmap secondImage)
{
    MemoryStream ms = new MemoryStream();
    firstImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    String firstBitmap = Convert.ToBase64String(ms.ToArray());
    ms.Position = 0;

    secondImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    String secondBitmap = Convert.ToBase64String(ms.ToArray());

    if (firstBitmap.Equals(secondBitmap))
    {
        return true;
    }
    else
    {
        return false;
    }
}

使用範例"指定路徑圖片判斷是否一致"

PictureBox pb = new PictureBox();
PictureBox pb2 = new PictureBox();
string str = Directory.GetCurrentDirectory() + "\\1.jpg";
string str2 = Directory.GetCurrentDirectory() + "\\2.jpg";
pb.Load(str);
pb2.Load(str2);
Bitmap bmp1 = new Bitmap(pb.Image);
Bitmap bmp2 = new Bitmap(pb2.Image);
bool Result = false;
Result = ImageCompareString(bmp1, bmp2);



2022年8月10日 星期三

[C#]除錯專用,當程式出現非預期錯誤或閃退

 在Main加入以下可在程式閃退前,提示訊息

static class Program
{
    /// <summary>
    /// 應用程式的主要進入點。
    /// </summary>
    [STAThread]
    static void Main()
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());


    }
    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        Console.WriteLine(e.ExceptionObject.ToString());
        MessageBox.Show(e.ExceptionObject.ToString());
    }
}

[C#]限定只開啟一個程序,防止重複啟動

 Main 中加入 以下

static void Main()
{
  //Other
  bool ret;
  System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret);
  if (ret)
  {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Form1());
  }
  else
  {
    MessageBox.Show(null, "This process is running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
    //   提示信息,可以刪除。  
    Application.Exit();//退出程式  
  }

}

2022年7月25日 星期一

[C#]啟動外部程式且切換工作目錄

 public static bool OpenPress(string FileName, string Arguments)//開啟外部檔案

{
    Process pro = new Process();
    if (System.IO.File.Exists(FileName))
    {
        //設定工作目錄為當前工作目錄
        string sPath = string.Empty;
        sPath = Path.GetDirectoryName(FileName).ToString();
        System.IO.Directory.SetCurrentDirectory(sPath);

        pro.StartInfo.FileName = FileName;
        pro.StartInfo.Arguments = Arguments;
        pro.StartInfo.CreateNoWindow = true;
        pro.StartInfo.UseShellExecute = false;
        pro.StartInfo.RedirectStandardInput = true;
        pro.StartInfo.RedirectStandardOutput = true;
        pro.StartInfo.CreateNoWindow = true;
        pro.Start();
        //切換為原工作目錄
        System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
        return true;
    }
    return false;
}

2022年6月22日 星期三

[C++] MFC CListCtrl Focus & Scroll

控鍵名稱為"IDC_LIST1"

EX01---範例

取得與設定List 焦點Focus

int iItem = 0;  
LPNMITEMACTIVATE temp = (LPNMITEMACTIVATE) pNMHDR;
iItem = temp->iItem;
((CListCtrl*)GetDlgItem(IDC_LIST1))->SetItemState(iItem,LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
((CListCtrl*)GetDlgItem(IDC_LIST1))->SetFocus();

EX02---範例

取得與設定Scrollbar 位置

int iItemScrollIndex = 0;
CRect crt;
((CListCtrl*)GetDlgItem(IDC_LIST1))->GetItemRect(0,crt,LVIR_BOUNDS);
m_iItemScrollIndex = ((CListCtrl*)GetDlgItem(IDC_LIST1))->GetTopIndex() * crt.Height();

((CListCtrl*)GetDlgItem(IDC_LIST1))->Scroll(CSize(0,iItemScrollIndex ));

2022年6月12日 星期日

[C++]把兩個char合併成一個char

 

測試環境:mfc 2019 

使用方式

unsigned char buff[2] = { '9','E' };

unsigned char ucResult = '0';

ucResult = catChar2Hex(buff[0], buff[1]);

CString cst;

cst.Format(L"%x", int(ucResult));

MessageBox(cst);


       結果: 0x9E

參考:https://blog.csdn.net/yhxxhy978/article/details/94136796


    unsigned char catChar2Hex(unsigned char hByte, unsigned char lByte)
    {
        unsigned char ucTmp = 0x00;
        unsigned char high, low;
        if (hByte >= 'A' && hByte <= 'F')
            high = hByte - 'A' + 10;
        else if (hByte >= 'a' && hByte <= 'f')
            high = hByte - 'a' + 10;
        else if (hByte >= '0' && hByte <= '9')
            high = hByte - '0';
        else
            ucTmp = 0xff;

        if (lByte >= 'A' && lByte <= 'F')
            low = lByte - 'A' + 10;
        else if (lByte >= 'a' && lByte <= 'f')
            low = lByte - 'a' + 10;
        else if (lByte >= '0' && lByte <= '9')
            low = lByte - '0';
        else
            ucTmp = 0xff;

        ucTmp = (high << 4) | (low << 0);
        return ucTmp;
    }

[SQL]顯示千分位與小數顯示

  CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) CONVERT style參數說明 1  (expression為 money 或 smallmoney型別): 0 : 預設,保留小數位後兩位,並四捨...