Skip to content

Instantly share code, notes, and snippets.

@HaruhiroTakahashi
Last active July 20, 2016 10:10
Show Gist options
  • Save HaruhiroTakahashi/ee03aaee14d51431915673ed85e31ea1 to your computer and use it in GitHub Desktop.
Save HaruhiroTakahashi/ee03aaee14d51431915673ed85e31ea1 to your computer and use it in GitHub Desktop.
C#メモ帳参考コード(中途半端)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyNotepad
{
//検索用、置換用の列挙型フラグ
public enum dialogMode
{
Find,
Replace
}
public partial class findDialog : Form
{
//処理対象となるTextBoxのインスタンスを保持
private TextBox _textBox;
//検索用か置換用のダイアログボックスを表示するかのフラグ
private dialogMode _mode;
private int findStartIndex = 0;
private int findCount = 0;
private string dialogTitle = "";
#region Constructor //コンストラクタ
public findDialog()
{
InitializeComponent();
}
public findDialog(TextBox txtBox)
{
InitializeComponent();
_textBox = txtBox;
}
public findDialog(dialogMode mode)
{
InitializeComponent();
Mode = mode;
}
public findDialog(dialogMode mode, TextBox txtBox)
{
InitializeComponent();
_textBox = txtBox;
Mode = mode;
}
#endregion
#region EventHandler //イベントハンドラ
//キャンセルボタン
private void cancelButton_Click(object sender, EventArgs e)
{
this.Close();
this.Dispose();
}
//検索ボタン
private void findButton_Click(object sender, EventArgs e)
{
replaceNextButton.Enabled = ExecFind();
//できれば一時停止させてKeyが押されたら再開するのを作りたい
//if (replaceNextButton.Enabled == true)
}
//置換ボタン
private void replaceNextButton_Click(object sender, EventArgs e)
{
if (_textBox.SelectionLength > 0) _textBox.SelectedText = ReplaceTextBox.Text;
replaceNextButton.Enabled = ExecFind();
}
//全て置換ボタン
private void replaceAllButton_Click(object sender, EventArgs e)
{
while (ExecFind())
{
if (_textBox.SelectionLength > 0) _textBox.SelectedText = ReplaceTextBox.Text;
};
}
//検索開始位置ラジオボタン
private void findPosition_Radio_CheckedChanged(object sender, EventArgs e)
{
topPosRadio.Checked = (currentPosRadio.Checked != true);
}
/*/検索後Enterキーを押された時
private void _textBox_KeyPress(object sender,KeyPressEventArgs e)
{
if(e.KeyPress == Keys.Enter)
findButton.Focus();
}*/
#endregion
#region Methods //メソッド
//検索用処理
private bool ExecFind()
{
//TextBoxコントロール内の文字列
string editString = _textBox.Text;
//検索を行う文字列
string findString = findTextBox.Text;
//検索を行う文字列の長さ
int findStringLength = findString.Length;
//検索開始位置の設定(先頭からラジオボタンが選択されている場合は 0 = 先頭を設定)
int findPoint = (topPosRadio.Checked) ? 0 : _textBox.SelectionStart;
//二回目以降の検索位置の指定
findStartIndex = (findStartIndex == 0) ? findPoint : findStartIndex;
//検索処理
findPoint = editString.IndexOf(findString, findStartIndex, (LgSmCheckBox.Checked) ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase);
//検索する文字列が見つからなかった場合
if (findPoint == -1)
{
string MSGBOX_FINDED_STRING = findDialog_Res.Msg_FindisDone;
string MSGBOX_REPLACED_STRING = findDialog_Res.Msg_ReplaseDone;
string msgboxString = (_mode == dialogMode.Find) ? MSGBOX_FINDED_STRING : findCount.ToString() + MSGBOX_REPLACED_STRING;
string msgbox_NothingWord = "\"" + findString + findDialog_Res.Msg_NotFound;
if (findCount != 0)
{
if (MessageBox.Show(this, msgboxString, dialogTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ResetFindPosition();
}
else
{
this.Close();
this.Dispose();
}
}
else
{ //検索の開始位置が現在位置からの場合、先頭から検索し直すか確認
if (currentPosRadio.Checked)
{
string msgbox_string = findDialog_Res.Msg_Current_Position + MSGBOX_FINDED_STRING;
if (MessageBox.Show(this, msgbox_string, dialogTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ResetFindPosition();
}
else
{
this.Close();
this.Dispose();
}
}
else
{
MessageBox.Show(this, msgbox_NothingWord, dialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
return false;
}
else
{
//見つかった文字を選択状態に
_textBox.Select(findPoint, findStringLength);
//TextBoxが選択された文字列を表示するようキャレットを移動
_textBox.ScrollToCaret();
//次を検索ボタンをクリックされた際の検索開始位置を設定
findStartIndex = findPoint + findStringLength;
//検索がヒットした回数をカウント
findCount++;
//テキストボックスにフォーカスをあてる
_textBox.Focus();
return true;
}
}
//TextBoxの検索位置をリセットする処理
private void ResetFindPosition()
{
findStartIndex = 0;
findCount = 0;
_textBox.SelectionStart = 0;
_textBox.Select(0, 0);
_textBox.Focus();
}
#endregion
#region property //プロパティ
//処理対象となるTextBoxのインスタンスを判断するためのプロパティ
public TextBox textBox
{
get { return _textBox; }
set { _textBox = value; }
}
//検索か置換のダイアログボックスを開く判断プロパティ
public dialogMode Mode
{
get { return _mode; }
set {
string DIALOGTITLE_FIND = findDialog_Res.Caption_Find;
string DIALOGTITLE_REPLACE = findDialog_Res.Caption_Replace;
_mode = value;
if (_mode == dialogMode.Find)
{
dialogTitle = DIALOGTITLE_FIND;
ReplacePanel.Visible = false;
}
else
{
dialogTitle = DIALOGTITLE_REPLACE;
ReplacePanel.Visible = true;
}
this.Text = dialogTitle;
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace MyNotepad
{
public partial class Form1 : Form
{
private bool dirtyFlag = false;   //ダーティーフラグ
private bool readOnlyFlag = false; //読み取り専用フラグ
private string editFilePath = ""; //編集中のファイルのパス
findDialog findDlg = null; //検索ダイアログボックスのインスタンスを格納
public Form1()
{
InitializeComponent();
}
#region OtherMethod
//ダーティーフラグの設定
private void setDirty(bool flag)
{
dirtyFlag = flag;
//読み取り専用でファイルがオープンされている場合、新規作成の場合
//[上書き(&S)] メニューアイテムは常に無効
menuSave.Enabled = (readOnlyFlag || editFilePath == "") ? false : flag;
}
//保存していない編集中のテキストがある場合に確認するための関数
private bool confirmDestructionText(string msgboxTitle)
{
const string MSG_BOX_STRING = "ファイルは保存されていません。\n\n編集中のテキストは破棄されます。\n\nよろしいですか?";
if (!dirtyFlag) return true;
return (MessageBox.Show(MSG_BOX_STRING, msgboxTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes);
}
//ステータスバーに保存日時を表示する関数
private void ShowSaveDateTime()
{
const string STATUS_STRING = "に保存しました";
//ステータスバー上のラベルに表示
toolStripStatusLabel1.Text = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + STATUS_STRING;
}
//フルパスの文字列からファイル名だけを取り出す関数
private string GetFileNameString(string filePath, char separateChar)
{
try
{
string[] strArray = filePath.Split(separateChar);
return strArray[strArray.Length - 1];
}
catch
{ return ""; }
}
#endregion
#region FileMenu
//[新規作成]メニューの処理
private void menuNew_Click(object sender, EventArgs e)
{
const string MSG_BOX_TITLE = "ファイルの新規作成"; //編集中のテキストがないか確認
if (confirmDestructionText(MSG_BOX_TITLE))
{
this.Text = "新規ファイル"; //アプリケーションのタイトルを変更
textBox1.Clear(); //テキストボックスの内容をクリア
editFilePath = ""; //編集中ファイルのパスをクリア
setDirty(false); //ダーティーフラグと[上書き..]メニューを設定
}
}
//[開く] メニューの処理
private void menuOpen_Click(object sender, EventArgs e)
{
openFileDlg.ShowDialog(this);
}
//=====OpenFileDialog の FileOK イベントハンドラ
private void openFileDlg_FileOk(object sender, CancelEventArgs e)
{
const string TITLE_EXTN_ReadOnly = " (読み取り専用)";
const string MSGBOX_TITLE = "ファイル オープン";
//選択されたファイルのパスを取得
editFilePath = openFileDlg.FileName;
//ファイルダイアログで読み取り専用が選択されたかどうかの値を取得
readOnlyFlag = openFileDlg.ReadOnlyChecked;
//読み取り専用で開いた場合にタイトル(ファイル名)に "読み取り専用" の文字をつける
this.Text = (readOnlyFlag)
? openFileDlg.SafeFileName + TITLE_EXTN_ReadOnly : openFileDlg.SafeFileName;
//ダーティーフラグのリセット
setDirty(false);
try
{
//テキストファイルの内容をテキストボックスにロード
textBox1.Text = File.ReadAllText(editFilePath, Encoding.Default);
}
catch (Exception ex)
{
//ファイルの読み込みでエラーが発生した場合に Exception の内容を表示
MessageBox.Show(this, ex.Message, MSGBOX_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//[上書き保存] メニューの処理
private void menuSave_Click(object sender, EventArgs e)
{
const string MSGBOX_TITLE = "ファイルの上書き保存";
//保存先のファイルが存在するかチェック
if (File.Exists(editFilePath))
{
try
{
//テキストボックスの内容をファイルに書き込み
File.WriteAllText(editFilePath, textBox1.Text, Encoding.Default);
//ダーティーフラグをリセット
setDirty(false);
//ステータスバーに保存日時を表示
ShowSaveDateTime();
}
catch (Exception ex)
{
//ファイルの書き込みでエラーが発生した場合に Exception の内容を表示
MessageBox.Show(this, ex.Message, MSGBOX_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
string MSG_BOX_STRING = "ファイル\"" + editFilePath
+ "\" のパスは正しくありません。\n\nディレクトリが存在するか確認してください。";
MessageBox.Show(MSG_BOX_STRING, MSGBOX_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
//=====[上書き保存(&S)] メニューアイテムを使用可能にする
private void textBox1_TextChanged(object sender, EventArgs e)
{
//ダーティーフラグを設定
setDirty(true);
}
//[名前をつけて保存]メニューの処理
private void menuSaveAdd_Click(object sender, EventArgs e)
{
//ファイルが新規作成だった場合の名前
const string NEW_FILE_NAME = "新規テキストファイル.txt";
//編集中のファイルのフルパスからファイル名だけを取得
string fileNameString = GetFileNameString(editFilePath, '\\');
//ファイル名が空白であった場合は "新規テキストファイル.txt" をセット
saveFileDlg.FileName = (fileNameString == "")
? NEW_FILE_NAME : fileNameString;
saveFileDlg.ShowDialog(this);
}
//=====保存ファイルへの書き込み処理
private void saveFileDlg_FileOk(object sender, CancelEventArgs e)
{
const string MSGBOX_TITLE = "名前を付けて保存";
//ファイルダイアログで指定された保存先パスを取得
editFilePath = saveFileDlg.FileName;
try
{
//ファイルの書き込み
File.WriteAllText(editFilePath, textBox1.Text, Encoding.Default);
//ファイル名をウィンドウのタイトルに設定
this.Text = GetFileNameString(editFilePath, '\\');
//ダーティーフラグのリセット
setDirty(false);
//ステータスバーに保存日時を表示
ShowSaveDateTime();
}
catch (Exception ex)
{
//エラー発生の際に Exception の内容を表示
MessageBox.Show(this, ex.Message, MSGBOX_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//[終了] メニューの処理
private void menuEnd_Click(object sender, EventArgs e)
{
const string MSGBOX_TITLE = "アプリケーションの終了";
if (confirmDestructionText(MSGBOX_TITLE))
{
this.Close();
this.Dispose();
}
}
#endregion
#region Editmenu
//[元に戻す]メニューの処理
private void menuUndo_Click(object sender, EventArgs e)
{
if (textBox1.CanUndo) //元に戻すことが可能であれば
{
textBox1.Undo();
textBox1.ClearUndo();
}
}
//[切り取り]メニューの処理
private void menuCut_Click(object sender, EventArgs e)
{
if (textBox1.SelectedText != "") textBox1.Cut();
}
//[コピー]メニューの処理
private void menuCopy_Click(object sender, EventArgs e)
{
if (textBox1.SelectedText != "") textBox1.Copy();
}
//[貼り付け]メニューの処理
private void menuPaste_Click(object sender, EventArgs e)
{
//クリップボードの内容がテキストで扱えるのであれば貼り付けを
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
textBox1.Paste();
}
//[削除]メニューの処理
private void menuDelete_Click(object sender, EventArgs e)
{
textBox1.Cut();
Clipboard.Clear();
}
private void menuFind_Click(object sender, EventArgs e)
{
//二重起動を防止
if(findDlg == null || findDlg.IsDisposed)
{
//検索ダイアログボックス用フォームのインスタンスを生成
findDlg = new findDialog(dialogMode.Find, textBox1);
//検索ダイアログボックスを表示
findDlg.Show(this);
}
}
private void menuReplace_Click(object sender, EventArgs e)
{
//二重起動を防止
if (findDlg == null || findDlg.IsDisposed)
{
//検索ダイアログボックス用フォームのインスタンスを生成
findDlg = new findDialog(dialogMode.Replace, textBox1);
//検索ダイアログボックスを表示
findDlg.Show(this);
}
}
private void menuJump_Click(object sender, EventArgs e)
{
}
//[全て選択] メニューの処理
private void menuAllSelect_Click(object sender, EventArgs e)
{
textBox1.SelectAll();
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment