C#のユーザーコントロールで、全角文字の張り付けを許可しないテキストボックスを作成する方法。
WM_PASTEメッセージ内で全角混じりの文字かどうかを調べて、全角混じりである場合はキャンセルしている。
using System.Text;
using System.Windows.Forms;
public class TextBoxEx : System.Windows.Forms.TextBox {
const int WM_PASTE = 0x302;
protected override void WndProc(ref Message m)
{
switch (m.Msg) {
case WM_PASTE:
// クリップボード内容を取得
object oClipboardText = Clipboard.GetDataObject().GetData(DataFormats.Text);
if (oClipboardText == null) {
return;
}
// 全角入力を許可しない場合、全角混じりの文字のペーストを許可しない
if (this.ImeMode == ImeMode.Disable) {
string sClipText = oClipboardText.ToString();
Encoding oSJisEncoding = Encoding.GetEncoding("Shift_JIS");
int nByteCnt = oSJisEncoding.GetByteCount(sClipText);
if (sClipText.Length != nByteCnt) {
return;
}
}
break;
}
base.WndProc(ref m);
}
}