歡迎跟我連絡

本頁最下方有Web MSN可以直接跟我交談喔!
免安裝程式...哈哈 歡迎聊天
顯示具有 Programming 標籤的文章。 顯示所有文章
顯示具有 Programming 標籤的文章。 顯示所有文章

2009年12月30日 星期三

XML Node 查詢操作

XML幾乎已經算是很廣泛的用於設定檔及一些資料的格式化存檔.既然如此,對它的內容的查詢就會經常的出現在程式之中,今天寫一個簡當的範例提供參考...

XML格式及內容:

<Names>
    <Name>
        <Name>Johnny</Name>
        <Tel>0926010111</Tel>
    </Name>
    <Name>
        <Name>Tim</Name>
        <Tel>0930817118</Tel>
    </Name>
</Names>

 

操作方式:

XmlDocument xml = new XmlDocument();
xml.Load(new StreamReader(myXmlString)); //myXmlString為上面檔案檔名
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
  string Name = xn["Name"].InnerText;
  string Tel = xn["Tel"].InnerText;
  Console.WriteLine("Name: {0} Tel: {1}", Name, Tel);
}

輸出:

Name: Johnmy Tel: 0926010111

Name: Tim Tel: 0930817118

71591080_fk3r586i_inbox3PICT0213 

檔案屬性操作

(1)取得檔案屬性

string filePath = @"c:\test.txt"; 

FileAttributes fileAttributes = File.GetAttributes(filePath);

(2)設定檔案屬性

// 清除所有檔案屬性

File.SetAttributes(filePath, FileAttributes.Normal);

// 只設定封存及唯讀屬性

File.SetAttributes(filePath, FileAttributes.Archive | FileAttributes.ReadOnly);

(3)檢查檔案屬性

// 檢查檔案是否有唯讀屬性

bool isReadOnly = ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);

// 檢查檔案是否有隱藏屬性

bool isHidden = ((File.GetAttributes(filePath) & FileAttributes.Hidden) == FileAttributes.Hidden);

// 檢查檔案是否有封存屬性

bool isArchive = ((File.GetAttributes(filePath) & FileAttributes.Archive) == FileAttributes.Archive);

// 檢查檔案是否有系統屬性

bool isSystem = ((File.GetAttributes(filePath) & FileAttributes.System) == FileAttributes.System);

(4)加入某些屬性給檔案

// 設定隱藏屬性   

File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.Hidden);

// 設定封存及唯讀屬性  

File.SetAttributes(filePath, File.GetAttributes(filePath) | (FileAttributes.Archive | FileAttributes.ReadOnly));

 

82167513_qzzWq8m4_ostuni1ostuni2217

2009年11月2日 星期一

Icon Finder

有時候程式寫後,也需要包裝一下,Icon算是門面級必須的包裝,這個網站提供了115,905 icons,只需要你動手收尋一下…

http://www.iconfinder.net/

2009-11-2 上午 08-46-28

搜尋結果

2009-11-2 上午 08-50-51

下載

2009-11-2 上午 08-51-38

2009年9月15日 星期二

常用時間(DateTime)字串格式整理

時間字串的格式化輸出是經常會用到的,尤其是程式會是系統的Log檔,為了明確的紀錄時間或是讓分析Log的工作更簡單,格式化的輸出尤其重要,一般來說都會使用String.Format來達到格式化的目的.看以下範例...

(1)自訂時間格式

specifiers
y 年
M 月
d 日
h 12小時制
H 24小時制
m 分
s 秒
f 毫秒
F 毫秒(不補0)
t 上午/下午
z 時區

DateTime myDT = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", myDT);  輸出=> "8 08 008 2008" 年份
String.Format("{0:M MM MMM MMMM}", myDT);  輸出=> "3 03 Mar March"月份
String.Format("{0:d dd ddd dddd}", myDT);  輸出=> "9 09 Sun Sunday" 日期
String.Format("{0:h hh H HH}",     myDT);  輸出=> "4 04 16 16"  時制 12/24
String.Format("{0:m mm}",          myDT);  輸出=> "5 05" 分
String.Format("{0:s ss}",          myDT);  輸出=> "7 07" 秒
String.Format("{0:f ff fff ffff}", myDT);  輸出=> "1 12 123 1230" 毫秒
String.Format("{0:F FF FFF FFFF}", myDT);  輸出=> "1 12 123 123" 毫秒(不補0)
String.Format("{0:t tt}",          myDT);  輸出=> "P PM"  上/下午
String.Format("{0:z zz zzz}",      myDT);  輸出=>  "-6 -06 -06:00"   時區

 

(2)標準時間格式(Framework提供)

Specifier     DateTimeFormatInfo     property Pattern value 
t                   ShortTimePattern              h:mm tt
d                  ShortDatePattern              M/d/yyyy
T                  LongTimePattern               h:mm:ss tt
D                 LongDatePattern                dddd, MMMM dd, yyyy
f                  (combination of D and t)     dddd, MMMM dd, yyyy h:mm tt
F                 FullDateTimePattern            dddd, MMMM dd, yyyy h:mm:ss tt
g                 (combination of d and t)      M/d/yyyy h:mm tt
G                (combination of d and T)     M/d/yyyy h:mm:ss tt
m, M            MonthDayPattern               MMMM dd
y, Y             YearMonthPattern               MMMM, yyyy
r, R             RFC1123Pattern                 ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
s                 SortableDateTi­mePattern    yyyy'-'MM'-'dd'T'HH':'mm':'ss
u                 UniversalSorta­ble               yyyy'-'MM'-'dd HH':'mm':'ss'Z'
                   DateTimePat­tern

String.Format("{0:t}", myDT);  輸出=>   "4:05 PM"                        
String.Format("{0:d}", myDT);  輸出=>   "3/9/2008"                       
String.Format("{0:T}", myDT);  輸出=>   "4:05:07 PM"                    
String.Format("{0:D}", myDT);  輸出=>   "Sunday, March 09, 2008"         
String.Format("{0:f}", myDT);  輸出=>   "Sunday, March 09, 2008 4:05 PM" 
String.Format("{0:F}", myDT);  輸出=>   "Sunday, March 09, 2008 4:05:07 PM"
String.Format("{0:g}", myDT);  輸出=>   "3/9/2008 4:05 PM"        
String.Format("{0:G}", myDT);  輸出=>   "3/9/2008 4:05:07 PM"           
String.Format("{0:m}", myDT);  輸出=>   "March 09"                      
String.Format("{0:y}", myDT);  輸出=>   "March, 2008"                   
String.Format("{0:r}", myDT);  輸出=>   "Sun, 09 Mar 2008 16:05:07 GMT" 
String.Format("{0:s}", myDT);  輸出=>   "2008-03-09T16:05:07"          
String.Format("{0:u}", myDT);  輸出=>   "2008-03-09 16:05:07Z"

 

59

2009年8月26日 星期三

陣列排序(Arrays Sorting) in C#

陣列可以透過Static Method Array.Sort來達到排序的目的.

(1) C# 基礎型別(Primitive types :int, double or string)

Int Array :

int[] intArray = new int[5] { 8, 10, 2, 6, 3 };
Array.Sort(intArray);
foreach (int i in intArray)
   Console.Write(i + " ");

輸出: 2 3 6 8 10

String Array :

string[] stringArray = new string[5] { "X", "B", "Z", "Y", "A" };
Array.Sort(stringArray);
foreach (string str in stringArray)
   Console.Write(str + " ");

輸出: A B X Y Z

(2)透過Delegate對自訂型別排序

定義類別

class User
{
     public string Name;
     public int Age;
     public User(string Name, int Age)

     {

        this.Name = Name;
        this.Age = Age;
     }
}

定義使用者資料

User[] users = new User[3]
              { new User("Betty", 23),
                new User("Susan", 20),
                new User("Lisa", 25)
              };

 

//根據姓名排序  Inline delegate
Array.Sort(users, delegate(User user1, User user2)
{
    return user1.Name.CompareTo(user2.Name);
}
);
foreach (User user in users)
     Console.Write(user.Name + ":" + user.Age + " ");  

輸出: Betty:23 Lisa:25 Susan:20

 

//根據年齡排序  Method Delegate
delegate int mySort(User user1, User user2);


Array.Sort(users, mySortMethod);
foreach (User user in users)
     Console.Write(user.Name + ":" + user.Age + " ");

private int mySortMethod(User user1, User user2)
{
       return user1.Age.CompareTo(user2.Age);
}

輸出: Susan20 Betty23 Lisa25)

(3)透過IComparable對自訂型別排序

定義類別

public class User : IComparable
{
  public string Name;
  public int Age;
  public User(string Name, int Age)
  {
     this.Name = Name;
     this.Age = Age;
  } 

  // implement IComparable interface
  public int CompareTo(object obj)
  {
    if (obj is User)
    {
      return this.Name.CompareTo((obj as User).Name);//根據姓名排序
    }
    throw new ArgumentException("Object is not a User");
  }
}

定義使用者資料

User[] users = new User[3]
              { new User("Betty", 23),
                new User("Susan", 20),
                new User("Lisa", 25)
              };

//根據姓名排序

Array.Sort(users);

 

2009-8-12 下午 01-02-48

2009年8月20日 星期四

螢幕結取與鍵盤HOOK 程式修正

剛剛測試了一下程式,發現記憶體越吃越兇...

於是修正一下程式

打開Source Code Form1.cs 修正底下(粗體字部分 請新增即可)

private void timer_Capture_Tick(object sender, EventArgs e)
{
    Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot);
    gfxScreenshot = Graphics.FromImage(bmpScreenshot);  
    gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);  
    string FileName = Path.Combine(textBox_FolderName.Text,string.Format(@"{0}.jpg", DateTime.Now.Ticks.ToString()));
    bmpScreenshot.Save(FileName, System.Drawing.Imaging.ImageFormat.Png);
    bmpScreenshot.Dispose();
    gfxScreenshot.Dispose();
}
private void timer_checkESC_Tick(object sender, EventArgs e)
{
    Application.DoEvents();
    GC.Collect();
    if (StopFlg)
        EndProcess();
}

不想修改者,這裡直接下再使用...

程式[MD5 : baac548d02f802c73640f5feda7a53a6]

 

2009-8-12 下午 12-41-13

2009年8月17日 星期一

Indexer(索引器) in C#

透過索引器機制,能夠讓你像陣列一樣的爲物件編寫索引值,這是屬性提供的一個有效率的方式來管理類別的實體資料,看以下範例

(1)建立Telephone Class

public class Telephnoe
{
    private string[] _telephone = new string[3];

    public string this[int index]
    {
        get
        {
            if(index >=0 || index < _telephone.Length)
             {
                 return _telephone[index];
             }
             return string.Empty;
         }
         set
         {
             if (index >= 0 || index < _telephone.Length)
             {
                 _telephone[index] = value;
             }
         }
     }
}

 

(2)建立Person Class

public class Person  
{  
      public string Name { get; set; }  
      public Telephone Telephones = new Telephone();  
}

使用範例:

// 宣告 Person 類別物件變數 Person  
Person myPerson = new Person();  
// 設定一般 Name 屬性,無法帶入參數  
person.Name = "王小明";  
// 設定可代入參數的 Telephones 屬性  
person.Telephones[0] = "07-3333333";  
person.Telephones[1] = "0960666333";  
// 讀取一般性 Name 屬性 
Console.WriteLine(person.Name); 
// 設定可代入參數的 Telephones 屬性 
Console.WriteLine(person.Telephones[0]); 
Console.WriteLine(person.Telephones[1]);

輸出結果:

王小明  
電話:07-3333333 
電話:0960666333

2009-8-12 下午 12-35-02

2009年8月16日 星期日

MP3 Tag 修改程式

想必各位一定都有聽MP3的習慣,但是有時候MP3 Player所顯示的資訊是錯誤的,或者是亂碼,怎麼辦???

這時候你就會需要MP3 Tag修改軟體.

MP3的 TAG大概是這樣組成的

MP3 TagBody (檔案的最後128 Bytes為TAG) 編碼方式 :
(0—2)      3 bytes ==> "TAG"三個字,如果不是"TAG",則為MPEG File
(3—32)     30 bytes ==> 標題 (Title)
(33—62)   30 bytes ==> 演唱/奏者,藝術家 (Artist)
(63—92)   30 bytes ==> 專輯名稱 (Album)
(93—96)   4bytes   ==> 發行年份 (PubYear)
(97—126) 30 bytes ==> 註釋/附加/備註信息 (Comment)
(127)       1 byte  ==> 音樂型態 (Music Type)

ID3v1 ID3v11

根據上面的編碼原則,寫的一個Parser Class

2009-8-16 下午 09-27-45

MP3TagParser Class

 

應用程式畫面

2009-8-16 下午 09-28-46

Source Code

2009年8月14日 星期五

防止程式重複啟動的方法(二)

曾經在一篇文章介紹過這個方法(請參考如何讓你的程式只能啟動一次 in C#)

今天再紹另一種方法 System.Diagnostics命名空間中的Process.GetProcessesByName…

範例程式如下:

Using System.Diagnostics;

...

private void FormMain_Load(object sender, EventArgs e)
{
       if (Process.GetProcessesByName(

                  Process.GetCurrentProcess().ProcessName).Length > 1)           

      {
          Dispose();
      }

}

在Form Load Event中,新增這段程式碼即可...

 

2009-8-12 下午 12-30-53

2009年8月12日 星期三

簡體中文 繁體中文 轉換

UI Layout如下圖所示:


重要的Using:
using System.Runtime.InteropServices;

重要程式碼:
namespace 簡繁中文轉換
{
public partial class Form1 : Form
{
internal const int LOCALE_SYSTEM_DEFAULT = 0x0800;
internal const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
internal const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;

//Import WIN32API:LCMapString
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int LCMapString(int Locale, int dwMapFlags, string lpSrcStr, int cchSrc, [Out] string lpDestStr, int cchDest);


public Form1()
{
InitializeComponent();
}

private void button_Translate_Click(object sender, EventArgs e)
{
if (textBox_TC.Text != string.Empty)
{
textBox_SC.Text = ToSimplified(textBox_TC.Text);
}
else if (textBox_SC.Text != string.Empty)
{
textBox_TC.Text = ToTraditional(textBox_SC.Text);
}
}
///


/// 繁體轉簡體
///

/// 要轉換的繁體字:體
/// 轉換後的簡體字:体
public static string ToSimplified(string pSource)
{
String tTarget = new String(' ', pSource.Length);
int tReturn = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_SIMPLIFIED_CHINESE, pSource, pSource.Length, tTarget, pSource.Length);
return tTarget;
}

/**////
/// 簡體轉繁體
///

/// 要轉換的繁體字:体
/// 轉換後的簡體字:體
public static string ToTraditional(string pSource)
{
String tTarget = new String(' ', pSource.Length);
int tReturn = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_TRADITIONAL_CHINESE, pSource, pSource.Length, tTarget, pSource.Length);
return tTarget;
}
}
}

參考資料:Win32 Programmer's Reference LCMapString

尚有其他轉換功能,可以自行研究
LOCALE_SYSTEM_DEFAULT = 0x0800;
LCMAP_FULLWIDTH = 0x00800000; //LCMAP_FULLWIDTH (轉全形字)
LCMAP_HALFWIDTH = 0x00400000; //LCMAP_HALFWIDTH (轉半形字)
LCMAP_HIRAGANA = 0x00100000; //LCMAP_HIRAGANA (轉成平假名,日文)
LCMAP_KATAKANA = 0x00200000; //LCMAP_KATAKANA (轉成片假名,日文)
LCMAP_LINGUISTIC_CASING = 0x01000000; //LCMAP_LINGUISTIC_CASINGLCMAP_UPPERCASE (不明)
LCMAP_LOWERCASE = 0x00000100; //LCMAP_LOWERCASE (轉小寫,應該是英文)
LCMAP_SIMPLIFIED_CHINESE = 0x02000000; //LCMAP_SIMPLIFIED_CHINESE (轉簡體)
LCMAP_SORTKEY = 0x00000400; //LCMAP_SORTKEY (不明)
LCMAP_TRADITIONAL_CHINESE = 0x04000000; //LCMAP_TRADITIONAL_CHINESE (轉繁體)
LCMAP_UPPERCASE = 0x00000200; //LCMAP_UPPERCASE (轉大寫,應該是英文)

2 8 10 16進位制轉換

UI Layout如下圖所示:

重要程式碼:
namespace 進制轉換
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox_From.SelectedIndex = 0;
comboBox_To.SelectedIndex = 2;
textBox_Source.Text = "0";
}

private void button1_Click(object sender, EventArgs e)
{
textBox_Result.Text = Convert2UrBase(textBox_Source.Text, int.Parse(comboBox_From.SelectedItem.ToString()), int.Parse(comboBox_To.SelectedItem.ToString())); }
public string Convert2UrBase(String Input_Value, int FromBase, int ToBase)
{
long RtnValue;
try
{
RtnValue = Convert.ToInt64(Input_Value, FromBase);
}
catch (Exception other)
{
RtnValue = 0;
}
return Convert.ToString(RtnValue, ToBase);
}

}
}

中華民國身分證驗證程式碼

驗證規則,如下圖所示




C#程式碼:
public bool CheckIdentificationId(string Input_ID)
{
bool IsTrue = false;
if (Input_ID.Length == 10)
{
Input_ID = Input_ID.ToUpper();
if (Input_ID[0] >= 0x41 && Input_ID[0] <= 0x5A)
{
int[] Location_No = new int[] { 10, 11, 12, 13, 14, 15, 16, 17, 34, 18, 19, 20, 21, 22, 35, 23, 24, 25, 26, 27, 28, 29, 32, 30, 31, 33 };
int[] Temp = new int[11];
Temp[1] = Location_No[(Input_ID[0]) - 65] % 10;
int Sum = Temp[0] = Location_No[(Input_ID[0]) - 65] / 10;
for (int i = 1; i <= 9; i++)
{
Temp[i + 1] = Input_ID[i] - 48;
Sum += Temp[i] * (10 - i);
}
if (((Sum % 10) + Temp[10]) % 10 == 0)
{
IsTrue = true;
}
}
}
return IsTrue;
}

應用範例:
bool Result = CheckIdentificationId(textBox_ID.Text);

C# 3.0提供Dictionary新的宣告法

這是3.0以前的宣告方式
Dictionary myDictionary = new Dictionary();
myDictionary.Add("Candy", "住址wwwwww");
myDictionary.Add("Jony", "住址xxxxx");
myDictionary.Add("Mary", "住址yyyyy");
myDictionary.Add("Nelson", "住址zzzzz");


3.0起,強化了Collection Initializer,所以你可以改成這樣的宣告
Dictionary dctNewWay = new Dictionary() {
{"Candy", "住址wwwwww"},
{"Jony", "住址xxxxx"},
{"Mary", "住址yyyyy"},
{"Nelson", "住址zzzzz"}
};

這樣的方式
就像是宣告固定元素的陣列
string[] NameList = { "Candy", "Jony", "Mary", "Nelson" };

2009年8月11日 星期二

修改字串編碼方式(Encoding)

有時候會出現顯示會出現亂碼,通常是編碼方式出了問題.
我們可以理用Encoding來解決這個問題...
範例程式:
string Source = "轉換編碼方式範例字串";
byte[] Target_BIG5 = Encoding.Default.GetBytes(Source ); //將字串轉為byte[], 中文版Default就是指BIG5編碼
byte[] Target_UTF8 = Encoding.Convert(Encoding.Default, Encoding.UTF8, Target_BIG5 );//轉碼Encoding.Convert(Source Encoder,Target Encoder , Source Variable)
MessageBox.Show(Encoding.UTF8.GetString(Target_UTF8 ));//顯示轉為UTF8後的字串

2009年7月31日 星期五

認證登錄系統圖片產生 .Net 控制項 (續)

下面圖片中的Circle或是Pie的圖形邊緣都有鋸齒出現不怎麼美觀.


找到IdentifyPictureControl.cs中這個DrawANewPicture() Function
加入下面粗體字那行,修正後就可以美觀一點了...
//Private Function
private void DrawANewPicture()
{
myPictureSize = this.Size;
GraphicsPath myGP = new GraphicsPath();
myBitmap = new Bitmap(this.Width, this.Height);
Graphics myG = Graphics.FromImage(myBitmap);
//GDI+ 修飾用屬性
myG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
myG.Clear(Color.White);
....

修正後,看起來舒服多了...

2009年7月30日 星期四

認證登錄系統圖片產生 .Net 控制項

繼續上一篇文章,將Class改寫為.Net控制項

新增一個Event,如果USER點選到圓圈(Circle),會產生Identify_OK Event.
新增一個屬性SharpNumber,可以設定圖形的複雜度.
新增一個Method GetNext(),可以重新繪製新的認證圖片.

程式碼:
1.IdentifyPictureControl.cspublic partial class IdentifyPictureControl : UserControl
{
//Private Variable
private Random myRandom = new Random();
private int mySharpNo;
private Size myPictureSize;
private Bitmap myBitmap;
private Region myRegion;
private Point myMouseLocation;
public int SharpNumber
{
set { mySharpNo = value; }
get { return mySharpNo; }
}
public IdentifyPictureControl()
{
InitializeComponent();
mySharpNo = 20;
myRegion = new Region();
myMouseLocation = new Point(-1, -1);
}

//Event
public event EventHandler Identify_OK;
protected virtual void OnIdentify_OK(EventArgs e)
{
if (Identify_OK != null)
{
Identify_OK(this, e);
}
}

//Private Component Event
private void IdentifyPictureControl_Load(object sender, EventArgs e)
{
DrawANewPicture();
this.BackgroundImage = myBitmap;
}
private void IdentifyPictureControl_Click(object sender, EventArgs e)
{
if (myRegion.IsVisible(myMouseLocation))
{
OnIdentify_OK(EventArgs.Empty);
}

}
private void IdentifyPictureControl_MouseMove(object sender, MouseEventArgs e)
{
myMouseLocation = e.Location;
}
private void IdentifyPictureControl_MouseLeave(object sender, EventArgs e)
{
myMouseLocation = new Point(-1, -1);
}

//Private Function
private void DrawANewPicture()
{
myPictureSize = this.Size;
GraphicsPath myGP = new GraphicsPath();
myBitmap = new Bitmap(this.Width, this.Height);
Graphics myG = Graphics.FromImage(myBitmap);
myG.Clear(Color.White);

//DrawEllipse
int mySize = GetSize(myPictureSize.Height);
Point myPoint = GetLocation(myPictureSize, mySize);
Pen myPen = new Pen(GetColor(), 3);
myG.DrawEllipse(myPen, new Rectangle(myPoint, new Size(mySize, mySize)));
myGP.AddEllipse(new Rectangle(myPoint, new Size(mySize, mySize)));
myRegion = new Region(myGP);

//DrawRectangle
for (int i = 0; i < mySharpNo/2; i++)
{
mySize = GetSize(myPictureSize.Height);
myPoint = GetLocation(myPictureSize, mySize);
myPen = new Pen(GetColor(), 3);
myG.DrawRectangle(myPen, new Rectangle(myPoint, new Size(mySize, mySize)));
}
for (int i = 0; i < mySharpNo/2; i++)
{
mySize = GetSize(myPictureSize.Height);
myPoint = GetLocation(myPictureSize, mySize);
myPen = new Pen(GetColor(), 3);
myG.DrawPie(myPen, new Rectangle(myPoint, new Size(mySize, mySize)), GetAngle(), GetAngle());
}
}
private Point GetLocation(Size PictureSize, int SharpWidth)
{
int X = myRandom.Next(0, PictureSize.Width - SharpWidth - 3); //3 Pen Width
int Y = myRandom.Next(0, PictureSize.Height - SharpWidth - 3); //3 Pen Width
return new Point(X, Y);
}
private int GetSize(int PictureWidth)
{
return (int)(PictureWidth / myRandom.Next(2, 6));
}
private Color GetColor()
{
switch (myRandom.Next(0, 10))
{
case 0:
return Color.Yellow;
case 1:
return Color.Violet;
case 2:
return Color.Green;
case 3:
return Color.DeepPink;
case 4:
return Color.DarkSlateBlue;
case 5:
return Color.DarkRed;
case 6:
return Color.CornflowerBlue;
case 7:
return Color.DarkSalmon;
case 8:
return Color.Gainsboro;
case 9:
return Color.Gold;
case 10:
return Color.Indigo;
default:
return Color.Black;
}
}
private float GetAngle()
{
return (float)(myRandom.Next(10, 350));
}

//Public method
public void GetNext()
{
DrawANewPicture();
this.BackgroundImage = myBitmap;
}
}

2.IdentifyPictureControl.Designer.cs
partial class IdentifyPictureControl
{
///


/// 設計工具所需的變數。
///

private System.ComponentModel.IContainer components = null;

///
/// 清除任何使用中的資源。
///

/// 如果應該公開 Managed 資源則為 true,否則為 false。
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region 元件設計工具產生的程式碼

///
/// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
///
///

private void InitializeComponent()
{
this.SuspendLayout();
//
// IdentifyPictureControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Name = "IdentifyPictureControl";
this.Size = new System.Drawing.Size(148, 148);
this.Load += new System.EventHandler(this.IdentifyPictureControl_Load);
this.MouseLeave += new System.EventHandler(this.IdentifyPictureControl_MouseLeave);
this.Click += new System.EventHandler(this.IdentifyPictureControl_Click);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.IdentifyPictureControl_MouseMove);
this.ResumeLayout(false);

}

#endregion

}

範例引用程式碼:
private void button1_Click(object sender, EventArgs e)
{
identifyPictureControl1.SharpNumber = 30;
identifyPictureControl1.GetNext();
}


private void identifyPictureControl1_Identify_OK(object sender, EventArgs e)
{
MessageBox.Show("OK");
}

2009年3月27日 星期五

小品: 利用遞迴計算n!階乘

函數:
public double N_step(int N)
{
return N == 1 ? 1 : N * N_step(N - 1);
}
應用:
textBox_Answer.Text = N_step(int.Parse(textBox_Value.Text)).ToString();

2009年3月4日 星期三

跨執行緒存取UI的一個方法

有時候WinFrom寫多執行緒時,卻出現了以下錯誤訊息
跨執行緒作業無效: 存取控制項 xxxxx 時所使用的執行緒與建立控制項的執行緒不同。

解決方法之一如下:
Form.CheckForIllegalCrossThreadCalls = false; //檢查開關

程式中有效管理大量資料的一個方法

有時候會遇到在程式中需要建立龐大的Array,ArrayList甚至是Queue.
可以運用下面方式(Pseudocode):

using System.Collections;
using System.Collections.Generic;
.....

Dictionary MyArryList = new Dictionary();
.....
//建立需要的ArryList
MyArryList.Add("同事資料", new ArrayList());
MyArryList.Add("朋友資料", new ArrayList());
MyArryList.Add("親戚資料", new ArrayList());
MyArryList.Add("同學資料", new ArrayList());

//使用
MyArryList["同事資料"][0] = ???;
MyArryList["同事資料"][1] = ???;
MyArryList["同事資料"][2] = ???;
MyArryList["同事資料"][3] = ???;

MyArryList["朋友資料"][0] = ???;
MyArryList["朋友資料"][1] = ???;
MyArryList["朋友資料"][2] = ???;
MyArryList["朋友資料"][3] = ???;
......

2008年11月22日 星期六

終於告一段落

忙了將近兩個半月,CASE終於完成所有主體架構.
雖然仍有一些地方要修改,但是也是動小刀而已.
CASE主要是將User于UI中設定好的東西,轉輸出為PDF檔案.
沒想到最關鍵竟然是CJK Font 輸出 及 RGB與CMYK的色彩轉換.
光是這兩部分就耗掉的我將近一個月的時間,找尋解決的方式.
我想要在外面接CASE混飯吃,還真是他媽的不簡單....
哈哈哈...

MSN狀態(我在線上時,可以跟我交談喔)