概要
cscの作法、調べてみた。
練習問題やってみた。
練習問題
RichTextBox に右クリックメニューを実装せよ。
参考にしたページ
写真
サンプルコード
using System;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.IO;
using System.Reflection;
class form1: Form {
RichTextBox rtxt;
ContextMenuStrip cms = new ContextMenuStrip();
form1() {
Text = "RichTextBox";
ClientSize = new Size(400, 400);
rtxt = new RichTextBox();
rtxt.Multiline = true;
rtxt.WordWrap = false;
rtxt.AcceptsTab = true;
rtxt.ScrollBars = RichTextBoxScrollBars.Both;
rtxt.Dock = DockStyle.Fill;
this.Controls.Add(rtxt);
cms.Opening += new CancelEventHandler(cms_Opening);
rtxt.ContextMenuStrip = cms;
}
void cms_Opening(object sender, CancelEventArgs e) {
ContextMenuStrip menuOnPanel = (ContextMenuStrip) sender;
Point mp = MousePosition;
menuOnPanel.SourceControl.PointToClient(mp);
cms.Items.Clear();
cms.Items.Add("コピー");
cms.Items[0].Click += PanelMenuItems0_Click;
cms.Items.Add("貼り付け");
cms.Items[1].Click += PanelMenuItems1_Click;
e.Cancel = false;
}
private void PanelMenuItems0_Click(object sender, EventArgs e) {
if (0 < rtxt.SelectionLength)
{
Clipboard.SetText(rtxt.Text.Substring(rtxt.SelectionStart, rtxt.SelectionLength));
}
rtxt.Focus();
}
private void PanelMenuItems1_Click(object sender, EventArgs e) {
int selectoin = rtxt.SelectionStart;
string insertString = Clipboard.GetText();
rtxt.Text = rtxt.Text.Substring(0, selectoin) + insertString + rtxt.Text.Substring(rtxt.SelectionStart + rtxt.SelectionLength);
rtxt.SelectionStart = selectoin + insertString.Length;
rtxt.SelectionLength = 0;
rtxt.Focus();
}
[STAThread]
public static void Main() {
Application.Run(new form1());
}
}
以上