C#: 付箋紙に文字を書き込む
2016/06/11
[ad#top-1]
- TextboxをLabelの上に覆うように配置する。
- Textboxは普段は非表示。
- LabelをダブルクリックするとTextboxが現れる。
- TextboxをダブルクリックするとTextboxが非表示になる
- Textboxの文字の内容がLabelにリンクが取られている。
前回はLabelのダブルクリックで終了するようになっていましたが、今回はTextBoxモードの際にフォームタイトルを出現させましたので、その際の×ボタンで終了するようになります。本当は右クリックウィンドウを出して終了メニューを出した方がアプリらしいのですが、今回は主旨から外れるので割愛しました。
using System.Drawing;
using System.Windows.Forms;
class StickyNote{
static void Main(){
Application.Run(new MainWindow());
}
}
class MainWindow : Form{
private Label label;
private TextBox text;
private Point mousePoint; //マウスのクリック位置を記憶
public MainWindow(){
this.Width = 200;
this.Height = 100;
this.FormBorderStyle = FormBorderStyle.None;
this.ShowInTaskbar = false;
//フォームに目いっぱいTextBoxを貼っておく。
text = new TextBox(){
Dock = DockStyle.Fill,
BackColor = Color.LightPink,
BorderStyle = BorderStyle.FixedSingle,
Multiline = true,
Visible = false,
Parent=this,
};
text.DoubleClick += new EventHandler(DoubleClicked);
//フォームに目いっぱいLabelを貼っておく。
label = new Label(){
Dock = DockStyle.Fill,
BackColor = Color.LightPink,
BorderStyle = BorderStyle.FixedSingle,
Parent=this,
};
label.DoubleClick += new EventHandler(DoubleClicked);
label.MouseDown += new MouseEventHandler(MouseDowned);
label.MouseMove += new MouseEventHandler(MouseMoved);
}
private void DoubleClicked(object sender, EventArgs e){
//TextBoxをダブルクリックしたらTextBoxを隠してテキスト文字をLabelにコピー
//フォームの枠も消す
if(sender==text){
text.Visible = false;
this.FormBorderStyle = FormBorderStyle.None;
label.Text = text.Text;
}
//LabelをダブルクリックしたらTextBoxを出現させる
//フォームの枠も出現
if(sender==label){
text.Visible = true;
this.FormBorderStyle = FormBorderStyle.Sizable;
}
}
//マウスのボタンが押されたとき
private void MouseDowned(object sender, MouseEventArgs e){
if ((e.Button & MouseButtons.Left) == MouseButtons.Left){
//位置を記憶する
mousePoint = new Point(e.X, e.Y);
}
}
//マウスが動いたとき
private void MouseMoved(object sender, MouseEventArgs e){
if ((e.Button & MouseButtons.Left) == MouseButtons.Left){
this.Location = new Point(
this.Location.X + e.X – mousePoint.X,
this.Location.Y + e.Y – mousePoint.Y);
}
}
}
[ad#ad-1]
スポンサーリンク