2023年12月4日 星期一

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

 

  • CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
    • CONVERT style參數說明1 (expression為 money 或 smallmoney型別):
      • 0 : 預設,保留小數位後兩位,並四捨五入,但沒有千分位逗點
      • 1: 保留小數位後兩位,並四捨五入,且有千分位逗點
      • 2: 沒有千分位逗點,小數點後四位(會四捨五入)

回傳含有千分位逗點的字串

SELECT CONVERT(VARCHAR(12), CONVERT(MONEY, '1234567'), 1)
// 查詢結果: 1,234,567.00

去除兩位小數.00

SELECT REPLACE(CONVERT(VARCHAR(12), CONVERT(MONEY, '1234567'), 1), '.00', '')
// 查詢結果: 1,234,567

SQL SERVER 2012 +

SQL Server 2012之後多了format指令可以使用

  • 2FORMAT ( value, format [, culture ] )

也可以使用format達到回傳千分位逗點

SELECT FORMAT(1234567, 'N')
// 查詢結果: 1,234,567.00

如不顯示小數點則改為

SELECT FORMAT(1234567, 'N0')
// 查詢結果: 1,234,567

2023年8月30日 星期三

[SQL]查詢sql server中使用狀態不是睡眠而是運行中的CPU狀態

以下語法 從記憶體取得資訊

並且可查看詳細資訊 



select * from sys.sysprocesses as a cross apply sys.dm_exec_sql_text( a.sql_handle )

where spid >50 and status <> 'sleeping'

order by cpu desc

2023年3月28日 星期二

[SQL]十進制轉二進制 用Function實現

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[FN_Convert10To2Bin](@i INT)
RETURNS VARCHAR(31)
AS
BEGIN
    DECLARE @str VARCHAR(31);
    SET @str=''

    WHILE (@i>0)
        SELECT @str=CAST(@i%2 AS VARCHAR(10))+@str, @i=@i/2
    RETURN(@str)

END
GO


呼叫方式
select dbo.[FN_Convert10To2Bin](10)

結果 1010

2023年3月24日 星期五

[C#]開啟外部程式方式

除了用以下方式:
https://rexyuan0502.blogspot.com/2019/01/c_11.html

也可以使用下列方式執行:

using System.Diagnostics;
using System.ComponentModel;

 class MyProcess
    {
        public string g_StrFullPath = "C:\\Test\\NSServer.exe";
        public string g_StrPath = "C:\\Test";
        public string g_StrName = "NSServer.exe";
        // Opens the Internet Explorer application.
        void OpenApplication(string myFavoritesPath)
        {
            // Start Internet Explorer. Defaults to the home page.
            Process.Start(g_StrFullPath);

            // Display the contents of the favorites folder in the browser.
            Process.Start(myFavoritesPath);
        }

        // Opens urls and .html documents using Internet Explorer.
        void OpenWithArguments()
        {
            // url's are not considered documents. They can only be opened
            // by passing them as arguments.
            Process.Start(g_StrFullPath, g_StrPath);

            // Start a Web page using a browser associated with .html and .asp files.
            Process.Start(g_StrFullPath, g_StrPath);
            Process.Start(g_StrFullPath, g_StrPath);
        }

        // Uses the ProcessStartInfo class to start new processes,
        // both in a minimized mode.
        void OpenWithStartInfo()
        {
            ProcessStartInfo startInfo = new ProcessStartInfo(g_StrFullPath);
            startInfo.WindowStyle = ProcessWindowStyle.Normal;

            Process.Start(startInfo);

            startInfo.Arguments = g_StrPath;

            Process.Start(startInfo);
        }

        public void Main()
        {
            // Get the path that stores favorite links.
            string myFavoritesPath =
                Environment.GetFolderPath(Environment.SpecialFolder.Favorites);

            MyProcess myProcess = new MyProcess();

            //myProcess.OpenApplication(myFavoritesPath);
            //myProcess.OpenWithArguments();
            myProcess.OpenWithStartInfo();
        }
    }


使用方式 可放到namespace 中 拆解使用

2022年12月8日 星期四

[C#]一般事件E EventArgs也能變成其他事件

 EventArgs是一個主要事件的基底基層,所以我們只要將EventArgs強制轉型成MouseEventArgs就好了

參考來源: https://cyfangnotepad.blogspot.com/2012/08/cnet-eventargs.html


private void lkl_ForgetPsw_DoubleClick(object sender, EventArgs e)
{
  MouseEventArgs Mouse = (MouseEventArgs)e;
  if (Mouse.Button == MouseButtons.Left)
  {
     MessageBox.Show("Ok");
   }

}

2022年10月23日 星期日

[C#]NuGet套件推薦-ILMerge

 使用WindowsForm開發時很常會引用許多dll或其他相關套件,

編譯成執行檔時,除執行檔外還會有許多dll或.Json的文件,不美觀外也不便給他人使用


使用此套件即可解決此問題


https://github.com/dotnet/ILMerge

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;
    }

2022年5月19日 星期四

[C#]使用json取得資料/取得多層

 使用環境VS2019
NuGet先加入Newtonsoft.json 
並且使用以下宣告

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

在mamespace中 宣告json要使用的結構類別

    public class cJsonDataItem

    {

        public string server { get; set; }

        public string database { get; set; }

        public string user { get; set; }

        public string password { get; set; }

        public string linkedserver { get; set; }

    }

在取得json 字串(下方用temp代替)後使用以下方式即可取得數值

string temp = "{    "accountingAck": {        "server": "127.0.0.1",        "database": "Accounting_Ack_AZ",        "user": "sa",        "password": "123456789",        "linkedserver": "REMOTE_LINK"    }}";

var dynamic_obj = JObject.Parse(temp);

string s = string.Empty;

StringBuilder strb = new StringBuilder();

StringBuilder strbb = new StringBuilder();

 

foreach (JProperty item in dynamic_obj.Children())

{

    strb.Append(item.Name);

    strbb.Append(item.Value);

}

StringBuilder strbc = new StringBuilder();

StringBuilder strbd = new StringBuilder();

dynamic darray = JsonConvert.DeserializeObject(strbb.ToString());   //此行為動態拿法 不用宣告最上面的類別

cJsonDataItem cjs = JsonConvert.DeserializeObject<cJsonDataItem>(strbb.ToString()); //此行需要使用最上面的類別cJsonDataItem

最終透過cjs 可以輕鬆拿取到各項的字串結果

temp = cjs.server;

temp = cjs.database;

            


2022年5月9日 星期一

[C#]程式焦點切換後恢復焦點的方式 foucs

 使用user32.dll 的Api,應用情境如以下:
在程式A上點擊按鈕後啟動B程式在背景執行,此時的焦點需要回到A程式
正常流程焦點會在B,透過以下方式可以將焦點設定為A


範例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Test
{
    public partial class PlayVoice : Form
    {
        public PlayVoice()
        {
            InitializeComponent();
        }


        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetForegroundWindow", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetF();             //獲得本窗體的控制代碼
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetF(IntPtr hWnd);    //設定此窗體為活動窗體

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.Handle != GetF())           //如果本視窗沒有獲得焦點
                SetF(this.Handle);                //設定本視窗獲得焦點
        }
    }
}

2022年5月4日 星期三

[C#]視窗在工具列點擊出現提示選單

 新增工具元件"notifyIcon" 與 "contextMenuStrip" 加到專案中

1.在Form.cs 的UI上選擇contextMenuStrip加入事件

2.到notifyIcon的屬性contextMenuStrip添加contextMenuStrip1元件名稱

3.到notifyIcon的事件 加入Click


using System.Reflection;

        private void notifyIcon1_Click(object sender, EventArgs e)

        {

            Type t = typeof(NotifyIcon);

            MethodInfo mi = t.GetMethod("ShowContextMenu", BindingFlags.NonPublic | BindingFlags.Instance);

            mi.Invoke(this.notifyIcon1, null);

        }

即可完成選單與通知

2022年4月7日 星期四

[C++]CString字符串分割

 #include <iostream>

#include <cstring> #include <atlcomtime.h> using namespace std; //最後一個參數返回的是子字符串的數量 CString * SplitString(CString str, char split, int& iSubStrs); int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; // initialize MFC and print and error on failur CString str = "sssdf sfds jieuri lj122 98098"; // CString str = "sfsfsf"; CString* pStr; int iSubStrs; pStr = SplitString(str, ' ', iSubStrs); //如果子字符串的數量爲1 if (iSubStrs == 1) { //Convert CString to char char* pCh = (LPSTR)(LPCTSTR)str; printf("%s\n", pCh); } else { //輸出所有子字符串 for (int i = 0; i < iSubStrs; i++) { //Convert CString to char char* pCh = (LPSTR)(LPCTSTR)pStr[i]; printf("%s\n", pCh); } delete []pStr; } system("pause"); return nRetCode; } CString * SplitString(CString str, char split, int& iSubStrs) { int iPos = 0; //分割符位置 int iNums = 0; //分割符的總數 CString strTemp = str; CString strRight; //先計算子字符串的數量 while (iPos != -1) { iPos = strTemp.Find(split); if (iPos == -1) { break; } strRight = strTemp.Mid(iPos + 1, str.GetLength()); strTemp = strRight; iNums++; } if (iNums == 0) //沒有找到分割符 { //子字符串數就是字符串本身 iSubStrs = 1; return NULL; } //子字符串數組 iSubStrs = iNums + 1; //子串的數量 = 分割符數量 + 1 CString* pStrSplit; pStrSplit = new CString[iSubStrs]; strTemp = str; CString strLeft; for (int i = 0; i < iNums; i++) { iPos = strTemp.Find(split); //左子串 strLeft = strTemp.Left(iPos); //右子串 strRight = strTemp.Mid(iPos + 1, strTemp.GetLength()); strTemp = strRight; pStrSplit[i] = strLeft; } pStrSplit[iNums] = strTemp; return pStrSplit; }

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

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