Tuesday, July 17, 2007

Common C# Trick

C# does not support to update UI from any other thread. So update UI from any other thread have a common trick. I am so dumb that I discover it every time and forget again. So write it in my blog so that it will be easier for me to find out next time. This is just a kind of GUI that read the hex version of any file. That's it.

Code... ... ...

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

namespace HEXReader

{

public partial class MainForm : Form

{

public delegate void ReaderEventHandler(string hexText, string charText);

public event ReaderEventHandler ReadEvent;

public MainForm()

{

InitializeComponent();

ReadEvent += new ReaderEventHandler(MainForm_ReadEvent);

}

void MainForm_ReadEvent(string hexText, string charText)

{

if (hexText != null && charText != null)

{

this.richTextBox1.Text += hexText;

this.richTextBox2.Text += charText;

}

else

{

MessageBox.Show("Finished");

}

}

private void button2_Click(object sender, EventArgs e)

{

Application.Exit();

}

private FileStream _in;

private void button1_Click(object sender, EventArgs e)

{

OpenFileDialog opneFile = new OpenFileDialog();

DialogResult _res = opneFile.ShowDialog(this);

if (_res == DialogResult.OK)

{

this.richTextBox2.Text = "";

this.richTextBox1.Text = "";

_in = (FileStream)opneFile.OpenFile();

System.Threading.Thread operationThread = new System.Threading.Thread(new System.Threading.ThreadStart(Start));

operationThread.Start();

this.textBox1.Text = opneFile.FileName;

}

}

private void Start()

{

Reader newReader = new Reader();

newReader.ReadEvent += new Reader.ReaderEventHandler(newReader_ReadEvent);

newReader.Read(this._in);

}

void newReader_ReadEvent(string hexText, string charText)

{

object[] oarray = new object[2];

oarray[0] = hexText;

oarray[1] = charText;

this.BeginInvoke(ReadEvent, oarray);

}

}

public class Reader

{

public delegate void ReaderEventHandler(string hexText, string charText);

public event ReaderEventHandler ReadEvent;

public void Read(FileStream _in)

{

if (_in.CanRead)

{

int _count = 0;

byte[] data = new byte[1024 * 8];

do

{

string charText = "";

string hexText = "";

_count = _in.Read(data, 0, 1024 * 8);

for (int index = 0; index < _count; index++)

{

byte _curr = (byte)data[index];

int _val = (0x0F & ((0xF0 & _curr) >> 4));

if (_val < 10)

hexText += _val.ToString();

else

hexText += (char)('A' + (_val - 10));

_val = 0x0F & _curr;

if (_val < 10)

hexText += _val.ToString();

else

hexText += (char)('A' + (_val - 10));

hexText += " ";

charText += (char)_curr;

}

if (ReadEvent != null)

ReadEvent(hexText,charText);

} while (_count > 0);

}

if (ReadEvent != null)

ReadEvent(null, null);

}

}

}

No comments:

Post a Comment

Please, no abusive word, no spam.