1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

cscの作法 その531

Posted at

概要

cscの作法、調べてみた。
練習問題やってみた。

練習問題

RichTextBox に右クリックメニューを実装せよ。

参考にしたページ

写真

image.png

サンプルコード

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());
	}
}





以上

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?