[C#]簡単なBIN2ASCIIテキストボックス
簡単なBIN2ASCIIテキストボックス
バイナリデータのテキスト入力からASCII変換するカスタムテキストボックスのたたき台。
2つのテキストボックスを用意し、一方はASCII表示用、一方はバイナリ文字表示用とした場合。
バイナリ側のテキストをカスタムテキストボックスに渡し、ASCIIで表示させる。
public class AsciiTextBox : TextBox
{
#region 定数
/// <summary>
/// PASTE Windowsメッセージ
/// </summary>
private const int WM_PASTE = 0x302;
#endregion
#region メソッド
/// <summary>
/// コンストラクタ
/// </summary>
public AsciiTextBox()
: base()
{
ImeMode = ImeMode.Disable;
}
/// <summary>
/// HEX文字列→ASCII変換
/// </summary>
/// <param name="binStr"></param>
public void HEX2ASCII(string binStr)
{
Encoding utf8 = Encoding.UTF8;
if (binStr.Length % 2 != 0)
{
// バイナリ文字列が2文字1セットでないとき、最終文字を削る
binStr = binStr.Remove(binStr.Length - 1, 1);
}
// バイト変換
Byte[] bytes = new Byte[binStr.Length / 2];
for (int i = 0; i < binStr.Length / 2; i++)
{
// バイナリ文字2文字で、1文字コードと判定し、配列に格納
string subStr = binStr.Substring(i * 2, 2);
int asciiCode = Convert.ToInt32(subStr, 16);
bytes[i] = (Byte)asciiCode;
}
// ASCII文字列生成
StringBuilder sb = new StringBuilder();
foreach (Byte b in bytes)
{
// 制御コードの時は代替文字を追加する
if (((0x00 <= (int)b) && ((int)b <= 0x1f)) || ((int)b == 0x7F))
{
sb.Append("・");
}
else
{
sb.Append(utf8.GetString(new Byte[] { b }));
}
}
Text = sb.ToString();
}
#region オーバーロード
/// <summary>
/// KeyPressオーバーロード
/// </summary>
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
// ASCII以外の入力を受け付けない
e.Handled = !((0x00 <= (int)e.KeyChar) && ((int)e.KeyChar <= 0x7F));
}
/// <summary>
/// WndProcオーバーロード
/// </summary>
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PASTE)
{
// ペーストを許可しない
return;
}
base.WndProc(ref m);
}
#endregion // オーバーロード
#endregion // メソッド
}