顯示具有 [C#] 標籤的文章。 顯示所有文章
顯示具有 [C#] 標籤的文章。 顯示所有文章

2014年6月25日 星期三

[C#/winform] MSChart使用實測+功能介紹

關於這個Microsoft Chart Control,網路上真的資料不多(不然就是簡體居多),有鑒於此,

這邊研究了很久以後...終於了解了一個大概,這邊寫一下心得跟使用說明。
























可以看到Series就代表一條線(或是一組線,或數據),你可以透過Series調整他的各項功能

ChartArea: 這線所畫的區域

ChartType: 要怎樣的圖形表示呢? 折線/直條/橫條...等

像我這這邊加入了4個Series,因為我要做四條線(但下面範例我只有設定2條而已)



這邊可以看到Legends代表上面那個線條註釋,而底下如果太多數據要顯示(內建會變成一個顯示一個不顯示)就要用程式碼修改為不重疊(交叉顯示)。

以下範例是參考 SUEHILARY的學習手記 修改而成的:

------------------------------------------------------------------------------------------------------------

            DateTime a = DateTime.Now;
            DateTime b = DateTime.Now;

            List<String> xValue = new List<string>();

            xValue.Add(a.ToString());
            xValue.Add(b.ToString());

            string[] titleArr = { "活動1", "活動2" };
            double[] yValues = { 269.23, 94 };
            double[] yValues2 = { 120.14, 116 };

            Chart1.Legends.Add("Legends1"); //圖例集合

            //設定 Chart
            Title title = new Title();
            title.Text = "統計圖";
            title.Alignment = ContentAlignment.MiddleCenter;
            title.Font = new System.Drawing.Font("Trebuchet MS", 14F, FontStyle.Bold);
            Chart1.Titles.Add(title);

            //設定 ChartArea----------------------------------------------------------------------
         
            //-----------------------------設定3D------------------------------//
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true; //3D效果
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = true; //並排顯示
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 40; //垂直角度
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 50; //水平角度
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.PointDepth = 10; //數據條厚度
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0; //外牆寬度
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.LightStyle = LightStyle.Realistic; //光源
            //-----------------------------設定3D------------------------------//

            Chart1.ChartAreas["ChartArea1"].BackColor = Color.FromArgb(240, 240, 240); //背景色
            Chart1.ChartAreas["ChartArea1"].AxisX.Enabled = AxisEnabled.True;
            Chart1.ChartAreas["ChartArea1"].AxisX2.Enabled = AxisEnabled.False; //隱藏 X2 標示
            Chart1.ChartAreas["ChartArea1"].AxisY2.Enabled = AxisEnabled.False; //隱藏 Y2 標示
            Chart1.ChartAreas["ChartArea1"].AxisY2.MajorGrid.Enabled = false;   //隱藏 Y2 軸線
            Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = Color.FromArgb(150, 150, 150);//X 軸線顏色
            Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = Color.FromArgb(150, 150, 150);//Y 軸線顏色


            Chart1.ChartAreas["ChartArea1"].AxisY.LabelStyle.Format = "#.###";//設定小數點

            //設定 Legends------------------------------------------------------------------------              
            Chart1.Legends["Legends1"].DockedToChartArea = "ChartArea1"; //顯示在圖表內
            //Chart1.Legends["Legends1"].Docking = Docking.Bottom; //自訂顯示位置
            Chart1.Legends["Legends1"].BackColor = Color.FromArgb(235, 235, 235); //背景色
            //斜線背景
            Chart1.Legends["Legends1"].BackHatchStyle = ChartHatchStyle.DarkDownwardDiagonal;
            Chart1.Legends["Legends1"].BorderWidth = 1;
            Chart1.Legends["Legends1"].BorderColor = Color.FromArgb(200, 200, 200);

            //設定 Series-----------------------------------------------------------------------
            //Chart1.Series["Series1"].ChartType = SeriesChartType.Line; //直條圖(Column),折線圖(Line),橫條圖(Bar)
            //Chart1.Series["Series2"].ChartType = SeriesChartType.Line; //直條圖(Column),折線圖(Line),橫條圖(Bar)
            //Chart1.Series["Series1"].ChartType = SeriesChartType.Bar; //橫條圖

            Chart1.Series["Series1"].Points.DataBindXY(xValue, yValues);//Series1的XY數值放入圖中

            Chart1.Series["Series1"].Legend = "Legends1";
            Chart1.Series["Series1"].LegendText = titleArr[0];
            Chart1.Series["Series1"].LabelFormat = "#.###"; //小數點
            Chart1.Series["Series1"].MarkerSize = 8; //Label 範圍大小
            Chart1.Series["Series1"].LabelForeColor = Color.FromArgb(0, 90, 255); //字體顏色
            //字體設定
            Chart1.Series["Series1"].Font = new System.Drawing.Font("Trebuchet MS", 10, System.Drawing.FontStyle.Bold);
            //Label 背景色
            Chart1.Series["Series1"].LabelBackColor = Color.FromArgb(150, 255, 255, 255);
            Chart1.Series["Series1"].Color = Color.FromArgb(240, 65, 140, 240); //背景色
            Chart1.Series["Series1"].IsValueShownAsLabel = true; // Show data points labels

            Chart1.Series["Series2"].Points.DataBindXY(xValue, yValues2);

            Chart1.Series["Series2"].Legend = "Legends1";
            Chart1.Series["Series2"].LegendText = titleArr[1];
            Chart1.Series["Series2"].LabelFormat = "#.###"; //小數點
            Chart1.Series["Series2"].MarkerSize = 8; //Label 範圍大小
            Chart1.Series["Series2"].LabelForeColor = Color.FromArgb(255, 103, 0);
            Chart1.Series["Series2"].Font = new System.Drawing.Font("Trebuchet MS", 10, FontStyle.Bold);
            Chart1.Series["Series2"].LabelBackColor = Color.FromArgb(150, 255, 255, 255);
            Chart1.Series["Series2"].Color = Color.FromArgb(240, 252, 180, 65); //背景色
            Chart1.Series["Series2"].IsValueShownAsLabel = true; //顯示數據

            Chart1.Series["Series3"].Color = Color.FromArgb(22, 24, 18, 65); //背景色

            Chart1.ChartAreas[0].AxisX.Interval = 1;   //設置X軸坐標的間隔為1
            Chart1.ChartAreas[0].AxisX.IntervalOffset = 1;  //設置X軸坐標偏移為1
            Chart1.ChartAreas[0].AxisX.LabelStyle.IsStaggered = true;   //設置是否交錯顯示,比如數據多的時間分成兩行來顯示

------------------------------------------------------------------------------------------------------------

原本應該是要先宣告

Chart Chart1 = new Chart();

但我們已經拉了一個元件叫Chart1因此就不用再new(再new就會重複,造成錯誤)

而Series1,2也是因為在winform當中有設定過因此無須重複設定(一樣造成錯誤)

3D的部分,因人而異,但個人是建議

            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = true; //並排顯示
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 40; //垂直角度
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 50; //水平角度
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.PointDepth = 10; //數據條厚度
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0; //外牆寬度
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.LightStyle = LightStyle.Realistic; //光源

這樣的設定比較好看,當然也可以改為不要並排顯示,一切取決於你的程式/數據多寡

背景色的部分應該無須多講解吧?

線條顏色修改的部分在Chart1.Series["Series"].Color = Color.FromArgb(自行設定色彩);

然後要修改Legend的文字則是在Chart1.Series["Series"].LegendText = "要顯示的文字";

目前遇到的問題跟解法都寫在這邊了,剩下的部分就等寫完再補一篇新的。

End

[C#] DateTime格式及如何運用

常常會用到DateTime,但每次都要上網查,所以寫下來以免忘記


1. DateTime.Now //記錄現在時間

這邊如果要顯示在winform一定要轉換成string,所以我們用.ToString()來轉換。

轉換出來結果一定是一長串"年/月/日 上/下午 小時:分鐘:秒"


2.進階轉換

DateTime.ToString("yyyymmdd") //20140625

DateTime.ToString("yyyy-mm-dd") //2014-06-25

DateTime.ToString("yyyy/m/d") //2014/6/25

DateTime.ToString("hh:mm:ss") // 11:12:13

DateTime.ToString("hh:mm")  //11:12

DateTime.ToString("T") //上午11:12:13

DateTime.ToString("t") //上午11:12:

DateTime.ToString("tt") //上午

3.只取某部分時間

DateTime.Minute.ToString(); //只取分鐘

DateTime.Second.ToString()//只取秒

....

4.計算時間差

TimeSpan  TS1 = new TimeSpan(DateTime.Tick); //DateTime部分請自行轉換成要計算的第一個數值
TimeSpan  TS2 = new TimeSpan(DateTime.Tick); //DateTime部分請自行轉換成要計算的第二個數值
TimeSpan Sub = TS1.subtract(TS2).Duration();

------------------------------------------------------------------------------------------------------------


DateTime用法不外乎上面幾項,用熟了即可

End

2014年6月24日 星期二

[C#/winform] MSchart,Microsoft chart,除了ZedGraph之外的另一個繪圖元件選擇+system.runtime.interopservices.COMexception解決方法

由於ZedGraph的外觀比較陽春,所以最近就來尋找有沒有更好的替代方案。

Google搜尋都是那幾篇文章轉貼來轉貼去,但遇到問題也沒有解決方案,

所以在這邊寫一下步驟:

1) 首先一定是下載跟安裝

http://www.microsoft.com/zh-tw/download/confirmation.aspx?id=14422

Microsoft Chart Controls for Microsoft .NET Framework 3.5


實測是發現為何是3.5,因為Framework4以後的都內建了....3.5SP1測試時候有點問題,

還沒找到解法。

2) 安裝以後,請到C:\Program Files\Microsoft Chart Controls\Assemblies 這邊,把dll們拉進工具列


然後會看到工具列出現一個Chart工具。

3) 拉進你的winform吧!(ASP.net也可以,他裡面有提供web.UI,但我沒寫ASP.net所以就交給高手處理了)


完成圖會長成這樣。

4) 遇到的問題

把dll檔加入參考中....於是出現 "無法加入Chart元.......system.runtime.interopservices.COMexception"

解決方法為: 刪除參考,即可。(ASP.net的解法是把<IIS>True</IIS> (不確定是不是正確) ,改為

false,拉入元件之後再重新開啟IIS)



2014年6月13日 星期五

[C#/winform] ComboBox + List

稍為紀錄一下,以免每次都忘記。

首先還是先用list把要用的資料add()進去,這點應該滿容易的。

只要記得加入的時候可以用條件是list<>.contain(內容)檢查是否已經存在list內了

然後如果要讓combobox能夠條列顯示list所有內容,就用ComboBox.DataSourse = List<> ;

這樣就可以把list所有內容都加入ComboBox選項內囉!

十分容易,end。

2014年5月9日 星期五

[C#] txt or csv檔案 多次重新讀取

通常我們讀檔都會使用StreamReader,但往往只能讀一次,無法從頭開始。

最基本的如下:

try
{
     using (StreamReader SR = new StreamReader(路徑)
    {
          string Line;

           while ((Line = SR.ReadLine()) != null) //一次讀一行
           {
                  string[] ReadLine_Array = Line.Split(',');//csv檔用逗號做分隔
                  //這邊可以處理文件
           }
     }
 }
 catch (IOException)
 { }
 catch (NullReferenceException)
 { }
 catch (FormatException)
 { }

在using裡面讀完一次就無法再從頭讀起,因此我們需要增加

StreamReader.ReadToEnd();//標頭拉到尾
StreamReader.BaseStream.Seek(0, SeekOrigin.Begin);//標頭重新回到最開始

增加以後就可以讓 檔案再次從頭讀起!

End

2014年4月22日 星期二

[C#] 如何打包exe檔 與 dll 檔?

相信很多人google關鍵字一定是會出現ILMerge這個工具,但今天要講得不是這個工具。

今天要介紹的是一個叫"Xenocode Postbuild 2010 for .Net" *(年份可能會更新,目前最新版本為

2010(好像也有看到2013,但不確定)



首先,進入Application ->Add(加入你要的dll + exe)


一次只能放一個exe檔,但可以多個dll檔


進入virtrualize->Enable(打勾)->Runtimes->Enabled .NET runtime engine: (選擇要的版本)

(底下有SQL,但我沒用到所以就沒選擇)



最後在Output分頁這邊,有一個Single application executable(當然你要選multiple application也是可以,

但功能不同)選曲要輸出的exe檔案後->按下Build Application->完成!

然後你的程式就可以在 "非.net環境下"(沒有安裝.net framework)執行!

低調載點: .

End

2014年4月16日 星期三

[C#/winform] 資料夾小功能-開啟路徑資料夾/指定MyDocument/程式起始路徑

由於在XP / Win7 的My Document路徑是不同的,因此如果程式內要設定建立資料夾或是儲存在

My Document資料夾下的話,就必須要撰寫特殊程式碼:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

最後的MyDocuments可以改為MyComputer之類的....請依照需要去變更。

另外如果想要開啟指定路徑的資料夾則是:

System.Diagnostics.Process.Start(路徑)

程式起始路徑的部分是當程式放在不同資料夾時會有不同的相對路徑,因此如果要取得目前路

徑就必須要靠程式碼:

Application.StartupPath

簡單,但是實用。

End

2014年4月14日 星期一

[C#winform] 小技巧:如何新增檔名到combo box內,並檢查時否有重複?

先看程式碼

string[] Dir_sub_file = Directory.GetFileSystemEntries(要新增到combo Box項目內的資料夾內檔案名稱);
foreach (string s in Dir_sub_file)
{
      file_list.Add(Path.GetFileNameWithoutExtension(s)); //檔案名稱清單 的list<string>陣列
}

foreach (string ss in file_list)
{
      if(!comboBox_SN_1.Items.Contains(ss))
           comboBox_SN_1.Items.Add(ss);
}

首先利用Directory.GetFileSystemEntires()來取得資料夾內檔案名稱,為了不要讓後面的附檔名出現

在combo Box的內容之中,因此這邊用Path.GetFileNameWithoutExtension(string 路徑)來除去附檔名,

然後利用foreach(也可以用for)來存入我們所建立的一個list<string>陣列 叫file_list。(功用只是存檔

名清單)

第二段foreach則是把file_list內所有的string都拿出來,利用comboBox.item.Contains(string)比對是否已

經有存在在comboBox內容中,如果沒有就用.add()這方法加入comboBox的items。

End


2014年2月27日 星期四

[C#/winform] DataGridView 隨視窗大小變動/列的Header加入文字/隱藏行,列

DataGridView 隨視窗大小變動

將DataGridView放入Form中,調整Dock(選中間那個) = Fill即可。


DataGridView 列的Header加入文字

要讓Row的Header加入文字,只要輸入

DataGridView1.Rows[第幾列].HeaderCell.Value = 文字 即可。

隱藏行,列

DataGridView.Columns[第幾行].Visble = false; //行

DataGridView.Rows[第幾列].Visble = false; //列

小技巧,但有大功用喔!

End


[C#/win32 API] SendMessage() 與 PostMessage()

網路上比較少SendMessage()跟PostMessage資料

先給SendMessage範例




SendMessage會等到接收端check後才會繼續執行,而PostMessage則是丟入訊息queue,繼續做。

以下範例都要先加入 using System.Runtime.InteropServices;

SendMessage A端(控制端):

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

using System.Runtime.InteropServices;
namespace TestA
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);
        uint MSG_SHOW = RegisterWindowMessage("Show Message");

        [DllImport("user32.dll")]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
     

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            IntPtr form_name = FindWindow(null, "要控制的視窗元件名稱(text,不是name)");//找B的IntPtr 用來代表指標或控制代碼

            if (form_name != IntPtr.Zero)
            {
                try
                {
                    int iNum = 9527;
                    SendMessage(form_name, MSG_SHOW, iNum, IntPtr.Zero);
                }
                catch (Exception)
                {
                }
            }
        }
    }
}

SendMessage B端(接收端):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TestB
{
    public partial class TestB_1 : Form
    {
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);
        uint MSG_SHOW = RegisterWindowMessage("Show Message");
        public TestB_1()
        {
            InitializeComponent();
        }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == MSG_SHOW)
            {
                label1.Text = (string)m.WParam.ToString();
            }
            base.WndProc(ref m);
        }
    }
}

PostMessage A端(呼叫端):

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

namespace postmessager
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
 
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
 
        private void post()
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr ptr = FindWindow(null, "post messager B");
            if (ptr != IntPtr.Zero)
            {
                int msg = 9527;
                PostMessage(ptr, msg, IntPtr.Zero, IntPtr.Zero);
            }
        }
    }
}

PostMessage B端(接收端):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace PostmessagerB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 9527)//m.Msg == MSG_SHOW
            {
                //label1.Text = (string)m.WParam.ToString();
                MessageBox.Show("9527");
            }
            base.WndProc(ref m);
        }
    }
}

至於為何可以使用SendMessage(),PostMessage(),FindWindow(),RegisterWindowMessage(),都是要先

import user32.dll (也就是[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] 後面為參數)

然後接收端使用WndProc (WindowProcess,我個人理解縮寫函意)去接收。

大部分程式碼也是參考網路上的,但大家都抄來抄去,而且我有修改程式碼,所以就不註明出處了(因為也不知道原始是誰的),當然我的版本是比較精簡化。

End

2014年2月19日 星期三

[C#/winform] 主Form / 副 Form 如何製作+連結2個Form

在VS2012裡面按 專案-> 加入windows form

你設定的檔名ex : form2

回到主Form,在要顯示的地方加入

Form2 frm2(這名稱可以改) =  new Form2();

frm2.showdialog(this); //show 副form

this.show(); //回到主form

即可。

[C#/Error] 不一致的存取範圍: 欄位型別 ...... 比欄位 ..... 存取範圍低

通常初學者寫Class不會特別宣告型別

但如果你宣告

public static Class名稱;
public Form
{
    ....
    ....
}
Class 名稱
{
    ......
}

這樣就有問題了!! 因為基本設定 Class沒加任何型別 = internal(內部可用)


Public > internal  所以 造成 "不一致的存取範圍: 欄位型別 ...... 比欄位 ..... 存取範圍低"的Error!

public static Class名稱;
public Form
{
    ....
    ....
}
public Class 名稱
{
    ......
}

這樣才對

End


[C#] List的基本用法

在寫程式常常會遇到要動態陣列,C#也很貼心的做了一個功能----泛型List<T>

但我想主要不是用在這邊....沒關係,還是講解一下List的用法

一開始一定就是

List<任意型態> 名稱 = new List<跟前面一樣的任意型態>();   //new給它一個空間

然後就可以在迴圈裡面丟給它值(它可以任意變動長度)

丟值的方法為: 名稱.Add(值);

如果要從中取出值就跟陣列一樣

名稱[0] (陣列位置可以改,這邊只是範例)

如果要長度 :名稱.Count 就會跟平常的.Length一樣囉!

範例:

List<byte> modbus = new List<byte>();

for (int i = 0; i < 30; i++)
{
       if (Modbus_save[i] == true) //這邊只是設一個條件而已
      {
            modbus.Add(Convert.ToByte(i)); //把i轉byte型態,存入List<T>
       }
}

End

2014年2月18日 星期二

[C#/winform] Form與Form之間 傳值

有許多方法可以傳值,包括Properties/Class/ini檔..等

這邊講兩個

1.Properties

使用時機: 需要儲存使用者設定時。

使用方法: 先到專案-> xxx屬性->設定,設定幾個需要使用的變數(型態要調好)

然後Form2內將變數代入Properties.Settings.Default.(設的變數名稱),

接著再去Form1內將Properties.Settings.Default.(設的變數名稱) 帶回form1(設一個新的變數去接)

記得要儲存使用者設定要加入Properties.Settings.Default.Save();


2.Class

使用時機: 滿廣泛的,但關掉無法儲存

使用方法: Form2內設一個public 變數

ex:

Public int a {get; set;}

public Form2{

....
}

回到Form1以後就可以用了,記得要寫在ShowDialog();的下方

Form2 frm2 = new Form2();

frm2.ShowDialog(this);

(寫在這邊)

當然要接值的話,型別也要對就是了。

End

2014年2月14日 星期五

[C#/winform] smtp傳送電子郵件(email)

using System.Net.Mail;
using System.Net;

   class Email
    {
        public string From {get;set; }
        public string To { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string Account { get; set; }
        public string Password { get; set; }
        public string Server { get; set; }
        public string Port { get; set; }
       
        public void Send_email()
        {
           //這邊先設定From,To,Subject,Body,Account,Password,Server,Port

            SmtpClient theSmtpClient = new SmtpClient(Server);
            NetworkCredential networkcredential = new NetworkCredential(Account, Password);//帳密
            theSmtpClient.UseDefaultCredentials = false;
            theSmtpClient.Credentials = networkcredential;
            int Int_port = Convert.ToInt32(Port);
            if (Int_port == 587)
            {
                theSmtpClient.EnableSsl = true;
            }
            else//不是587 就是 25
            {
                theSmtpClient.EnableSsl = false;
            }
            theSmtpClient.Port = Int_port;

            try
            {
                theSmtpClient.Send(From, To, Subject, Body);
            }
            catch (Exception)
            {

            }
        }
    }

十分簡單,不過要注意的地方就是Port在有SSL加密認證的環境下要用587(ex:gmail),沒有的話則用25即可,然後Using要加入net / net.mail

End

2014年2月13日 星期四

[C#/winform] 呼叫外部程式(傳入參數) + 不會顯示出來 + 結束強制關閉程式

本篇分成三部份來講

a)呼叫外部程式

//呼叫程式(啟動)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;

namespace Activate_exe
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主要進入點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            string target = 目標路徑;

            ProcessStartInfo pInfo = new ProcessStartInfo(target);
            pInfo.Arguments = "我是參數";
            using (Process p = new Process())
            {
                p.StartInfo = pInfo;
                p.Start();
            }

        }
    }
}


//主程式(被呼叫)
//在Program.cs內部
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace (被呼叫的程式,名稱自行更改)
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主要進入點。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (args.Length == 0)
            {
                Application.Run(new Form1());
            }
            else
            {
                Application.Run(new Form1(args[0].ToString()));
            }
        }
    }
}

呼叫程式十分簡單,也不需要用到winform,就直接寫在Program.cs即可

一開始記得要加入"using System.Diagnostics;"不然ProcessStartInfo 沒法用,

new一個ProcessStartInfo(要呼叫的程式路徑),然後 ProcessStartInfo.Argument內就是要傳的參數。

(參數遇到空格 疑似可以用\" (http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/88415.aspx)來解決)

傳多個參數,就是使用空格作為分隔 參數A空格B,在Form1値得注意的地方就是有兩個多載,當

沒有參數傳來的時後就用Form1(),有則Form1(args[])



-----------------------------------------------------------------------------------------------------------

被呼叫的程式要接參數,所以main(string[] args

主程式//Form1.cs

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

namespace Argument_IN_exe
{
    public partial class Form1 : Form
    {
        private string _args;
        public Form1()
        {
            InitializeComponent();

        }

        public Form1(string value)
        {
            InitializeComponent();
            if (!string.IsNullOrEmpty(value))
            {
                _args = value;
                MessageBox.Show(_args);
            }
        }
    }
}

b)不會顯示出來

要讓程式一開啟就不顯示出來,目前只知道這個方法(最小化+不顯是在系統列)

寫在Form load事件當中,一讀就縮最小,但是有個問題就是你無法停止它(所以才需要

c.強制關閉程式)

private void Form1_Load_1(object sender, EventArgs e)
{
       this.WindowState = FormWindowState.Minimized;
       this.ShowInTaskbar = false;
       this.Hide();
}

private void Form1_Shown(object sender, EventArgs e)
{
      this.Hide();
}


c)結束強制關閉程式

光有Close()是不夠的,可以試試看Ctrl+Alt+Del,會發現沒有全部關完。

加入Enviroment這行吧!

this.Close();
Environment.Exit(Environment.ExitCode);

參考: http://www.dotblogs.com.tw/atowngit/archive/2009/12/26/12681.aspx


2014年2月12日 星期三

[C#/winform] Notifyicon(系統列圖示) + ContextMenuStrip(右鍵選單) 設定

首先,先到工具列拉出NotifyIcon 與 ContextMenuStrip兩個工具

NotifyIcon是系統列工具,可以改變圖示(如果覺得它很醜)

ContextMenuStrip則是應用在圖示上面按滑鼠右鍵會出現的選單

如果一開始就不要讓程式show出來,請寫入

            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;

這樣起始畫面就會縮到最小。(這段要寫再Form Load事件裡面!!)

在ContextMenuStrip當中新增一個選項ex: Exit ,接著點它兩下

進入程式部分:(這邊看要怎樣打都可以)

 this.Close();//exit代表關掉程式

最後,在Notify icon的工具欄當中把ContextMenuStrip那一欄改為你所拉進來的ContextMenuStrip的

名稱,這樣它會直接去抓那個工具,很簡單,但是很實用喔!

End


2014年2月11日 星期二

[C#/Serialize] 簡易版本-Serailize/Deserialize

上一篇序列化/反序列化比較難,這次寫一點簡單的。

首先一樣先建一個類別庫(新增專案->類別庫)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Solar_stucture
{
    [Serializable]
    public class Solar_read
    {
        public byte Adress = 0;
        public byte Function_code = 0;
        public byte Byte_count = 0;
    }
}

然後建製(F9) 會產生錯誤,很正常。但不是錯誤。(在Debug資料夾內會有.dll檔)

接著,開個新的專案。然後  專案->加入參考...(瀏覽->選剛剛產生的dll檔)

在主程式(或任何你想要加的地方)加入

Solar_read Read_protocol = new Solar_read();

然後使用Read_protocol.Adress,你會發現可以使用!!

沒錯,就把東西存進去(型別要對)

都加完了以後,開始寫入檔案。

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("Read Protocol.dat", FileMode.Create, FileAccess.Write,       FileShare.Read);
            formatter.Serialize(stream, Read_protocol);
            stream.Close();

記得dll檔那邊要有[Serializable]不然這邊執行上會出現serialize的異常。序列化到此結束!


基本的反序列化也十分簡單:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Solar_stucture;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace SolarControl_Front
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(序列化存的檔案路徑, FileMode.Open, FileAccess.Read, FileShare.Read);
            Solar_read read = (Solar_read)formatter.Deserialize(stream);
            MessageBox.Show(read.Adress.ToString());
            stream.Close();

        }
    }
}

一樣的東西,只是變成Deserialize(Stream stream),接的格式是用你所創建的Class格式喔!

MessageBox只是確認有弄對而已。 Over

[C#/進制轉換] byte資料 轉換 ASCII碼

先看看程式碼

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

namespace ByteToASCII
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[] toASCII = new byte[4];
            toASCII[0] = Convert.ToByte(textBox1.Text,10);
            toASCII[1] = Convert.ToByte(textBox2.Text,10);
            toASCII[2] = Convert.ToByte(textBox3.Text,10);
            toASCII[3] = Convert.ToByte(textBox4.Text,10);

            textBox5.Text = System.Text.Encoding.ASCII.GetString(toASCII);
        }
    }
}

先new一個byte陣列,利用Convert.ToByte(String,多少進位)來轉換,存如byte陣列當中

之後用Sytem.Text.Encoding.ASCII.GetString(byte陣列) 即可轉換

End

2014年2月10日 星期一

[C#/Serialize] 在不同檔案間傳遞結構(structure)利用Serialize和Deserialize

首先必須先創建一個"類別庫"(新增->類別庫 in VS2012)

一定要有關鍵字[Serializable]否則無法,然後建立一個Struct

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel;

namespace PassingStruct
{
    public class Class1
    {
    }

    [Serializable]
    public struct MemberList
    {
        private BindingList<Member> _MemberCollection;
        public BindingList<Member> MemberCollection
        {
            get
            {
                if (this._MemberCollection == null)
                    this._MemberCollection = new BindingList<Member>();
                return this._MemberCollection;
            }
        }
    }

    [Serializable]
    public struct Member
    {
        public int ID { get; set; }
        public int age { get; set; }
        public string name { get; set; }
        public int number { get; set; }
        public string sex { get; set; }
    }
}

編譯時會產生錯誤訊息,但其實還是成功(在Debug資料夾內)會有一個dll檔產生。

OK,到這邊,需要將dll檔加入參考到要序列化的程式碼。

以下為序列化程式碼

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


using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using PassingStruct;

namespace Binary_filestreame
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
         
        }

        private void button1_Click(object sender, EventArgs e)
        {

            PassingStruct.MemberList list = CreateClass();
            SerializeToBinary("list.dat", list);
        }
        public PassingStruct.MemberList CreateClass()
        {
            PassingStruct.MemberList list = new PassingStruct.MemberList();
            list.MemberCollection.Add(new PassingStruct.Member() { ID = 1, age = 18, name = "paul walker", number = 999, sex = "male" });
            list.MemberCollection.Add(new PassingStruct.Member() { ID = 2, age = 20, name = "jonathan brewster", number = 123, sex = "female" });
            return list;
        }
        public static void SerializeToBinary(string FileName, object Object)
        {
            Stream stream = null;
            IFormatter/*用於格式化已經序列化的東西*/ format = new BinaryFormatter();//以二進位格式序列化和還原序列化物件
            try
            {
                stream = new FileStream(FileName,FileMode.Create,FileAccess.Write,FileShare.Read);
                format.Serialize(stream, Object);
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PassingStruct.MemberList list = DeserializeFromBinary<PassingStruct.MemberList>("list.dat");
        }

        public static T DeserializeFromBinary<T>(string FileName)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = null;
            try
            {
                stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                object obj = formatter.Deserialize(stream);
                if (obj == null)
                    return default(T);
                else
                    return (T)obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }
    }
}

注意到在using這邊
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using PassingStruct;//這個就是dll檔,除了在Visual Studio專案裡面選擇 專案->加入參考->瀏覽->dll檔,還要加入這一行

然後,序列化基本上就完成了。接著就是反序列化:(以下為反序列化程式碼)

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

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using PassingStruct;

namespace serialize_transfer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //File.wr
        }

        public static T DeserializeFromBinary<T>(string FilePath)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = null;
            try
            {
                stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                object obj = formatter.Deserialize(stream);//問題出在這邊
                if (obj == null)
                    return default(T);
                else
                    return (T)obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PassingStruct.MemberList list = DeserializeFromBinary<PassingStruct.MemberList>(@"C:\Users\daniel\Dropbox\Visual Studio 2012\Projects\Binary_filestreame\Binary_filestreame\bin\Debug\list.dat");
        }
    }
}

同樣也需要加入參考以及+using的程式碼 記得反序列化路徑要弄對就好了。

應用的部分,可使用在DataGridView上面

BindingSource Source = new BindingSource();
public void Form1_Load(object sender, EventArgs e)
{
    this.Source.DataSource = CreateClass().MemberCollection;

    this.dataGridView1.DataSource = this.Source;
    this.bindingNavigator1.BindingSource = this.Source;
    this.textBox1.DataBindings.Add("Text", this.Source, "ID");
    this.textBox2.DataBindings.Add("Text", this.Source, "name");
    this.textBox3.DataBindings.Add("Text", this.Source, "age");
    this.textBox4.DataBindings.Add("Text", this.Source, "phone");
    this.textBox5.DataBindings.Add("Text", this.Source, "sex");
}

End

參考資料: 余小章.net教學