Windows Forms textbox that has line numbers? - c#

I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too.
Does anyone know of a premade component that could do this?

Referencing Wayne's post, here is the relevant code. It is using GDI to draw line numbers next to the text box.
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
SetStyle(ControlStyles.UserPaint, True)
SetStyle(ControlStyles.AllPaintingInWmPaint, True)
SetStyle(ControlStyles.DoubleBuffer, True)
SetStyle(ControlStyles.ResizeRedraw, True)
End Sub
Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged
FindLine()
Invalidate()
End Sub
Private Sub FindLine()
Dim intChar As Integer
intChar = RichTextBox1.GetCharIndexFromPosition(New Point(0, 0))
intLine = RichTextBox1.GetLineFromCharIndex(intChar)
End Sub
Private Sub DrawLines(ByVal g As Graphics, ByVal intLine As Integer)
Dim intCounter As Integer, intY As Integer
g.Clear(Color.Black)
intCounter = intLine + 1
intY = 2
Do
g.DrawString(intCounter.ToString(), Font, Brushes.White, 3, intY)
intCounter += 1
intY += Font.Height + 1
If intY > ClientRectangle.Height - 15 Then Exit Do
Loop
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
DrawLines(e.Graphics, intLine)
End Sub
Private Sub RichTextBox1_VScroll(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.VScroll
FindLine()
Invalidate()
End Sub
Private Sub RichTextBox1_UserScroll() Handles RichTextBox1.UserScroll
FindLine()
Invalidate()
End Sub
The RichTextBox is overridden like this:
Public Class UserControl1
Inherits System.Windows.Forms.RichTextBox
Public Event UserScroll()
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = &H115 Then
RaiseEvent UserScroll()
End If
MyBase.WndProc(m)
End Sub
End Class
(Code by divil on the xtremedotnettalk.com forum.)

Take a look at the SharpDevelop C# compiler/IDE source code. They have a sophisticated text box with line numbers. You could look at the source, figure out what they're doing, and then implement it yourself.
Here's a sample of what I'm referencing:
(source: sharpdevelop.net)

There is a project with code available at http://www.xtremedotnettalk.com/showthread.php?s=&threadid=49661&highlight=RichTextBox.
You can log into the site to download the zip file with the user/pass: bugmenot/bugmenot

There is a source code editing component in CodePlex for .net,
http://www.codeplex.com/ScintillaNET

Here's some C# code to do this. It's based on the code from xtremedotnettalk.com referenced by Wayne. I've made some changes to make it actually display the editor text, which the original didn't do. But, to be fair, the original code author did mention it needed work.
Here's the code (NumberedTextBox.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace NumberedTextBoxLib {
public partial class NumberedTextBox : UserControl {
private int lineIndex = 0;
new public String Text {
get {
return editBox.Text;
}
set {
editBox.Text = value;
}
}
public NumberedTextBox() {
InitializeComponent();
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
editBox.SelectionChanged += new EventHandler(selectionChanged);
editBox.VScroll += new EventHandler(OnVScroll);
}
private void selectionChanged(object sender, EventArgs args) {
FindLine();
Invalidate();
}
private void FindLine() {
int charIndex = editBox.GetCharIndexFromPosition(new Point(0, 0));
lineIndex = editBox.GetLineFromCharIndex(charIndex);
}
private void DrawLines(Graphics g) {
int counter, y;
g.Clear(BackColor);
counter = lineIndex + 1;
y = 2;
int max = 0;
while (y < ClientRectangle.Height - 15) {
SizeF size = g.MeasureString(counter.ToString(), Font);
g.DrawString(counter.ToString(), Font, new SolidBrush(ForeColor), new Point(3, y));
counter++;
y += (int)size.Height;
if (max < size.Width) {
max = (int) size.Width;
}
}
max += 6;
editBox.Location = new Point(max, 0);
editBox.Size = new Size(ClientRectangle.Width - max, ClientRectangle.Height);
}
protected override void OnPaint(PaintEventArgs e) {
DrawLines(e.Graphics);
e.Graphics.TranslateTransform(50, 0);
editBox.Invalidate();
base.OnPaint(e);
}
///Redraw the numbers when the editor is scrolled vertically
private void OnVScroll(object sender, EventArgs e) {
FindLine();
Invalidate();
}
}
}
And here is the Visual Studio designer code (NumberedTextBox.Designer.cs)
namespace NumberedTextBoxLib {
partial class NumberedTextBox {
/// Required designer variable.
private System.ComponentModel.IContainer components = null;
/// Clean up any resources being used.
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
private void InitializeComponent() {
this.editBox = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// editBox
//
this.editBox.AcceptsTab = true;
this.editBox.Anchor = ((System.Windows.Forms.AnchorStyles) ((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.editBox.Location = new System.Drawing.Point(27, 3);
this.editBox.Name = "editBox";
this.editBox.Size = new System.Drawing.Size(122, 117);
this.editBox.TabIndex = 0;
this.editBox.Text = "";
this.editBox.WordWrap = false;
//
// NumberedTextBox
//
this.Controls.Add(this.editBox);
this.Name = "NumberedTextBox";
this.Size = new System.Drawing.Size(152, 123);
this.ResumeLayout(false);
}
private System.Windows.Forms.RichTextBox editBox;
}
}

I guess it depends on the Font size, I used "Courier New, 9pt, style=bold"
Added fix for smooth scrolling, (not line by line)
Added fix for big files, when scroll value is over 16bit.
NumberedTextBox.cs
public partial class NumberedTextBox : UserControl
{
private int _lines = 0;
[Browsable(true),
EditorAttribute("System.ComponentModel.Design.MultilineStringEditor, System.Design","System.Drawing.Design.UITypeEditor")]
new public String Text
{
get
{
return editBox.Text;
}
set
{
editBox.Text = value;
Invalidate();
}
}
private Color _lineNumberColor = Color.LightSeaGreen;
[Browsable(true), DefaultValue(typeof(Color), "LightSeaGreen")]
public Color LineNumberColor {
get{
return _lineNumberColor;
}
set
{
_lineNumberColor = value;
Invalidate();
}
}
public NumberedTextBox()
{
InitializeComponent();
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
editBox.SelectionChanged += new EventHandler(selectionChanged);
editBox.VScroll += new EventHandler(OnVScroll);
}
private void selectionChanged(object sender, EventArgs args)
{
Invalidate();
}
private void DrawLines(Graphics g)
{
g.Clear(BackColor);
int y = - editBox.ScrollPos.Y;
for (var i = 1; i < _lines + 1; i++)
{
var size = g.MeasureString(i.ToString(), Font);
g.DrawString(i.ToString(), Font, new SolidBrush(LineNumberColor), new Point(3, y));
y += Font.Height + 2;
}
var max = (int)g.MeasureString((_lines + 1).ToString(), Font).Width + 6;
editBox.Location = new Point(max, 0);
editBox.Size = new Size(ClientRectangle.Width - max, ClientRectangle.Height);
}
protected override void OnPaint(PaintEventArgs e)
{
_lines = editBox.Lines.Count();
DrawLines(e.Graphics);
e.Graphics.TranslateTransform(50, 0);
editBox.Invalidate();
base.OnPaint(e);
}
private void OnVScroll(object sender, EventArgs e)
{
Invalidate();
}
public void Select(int start, int length)
{
editBox.Select(start, length);
}
public void ScrollToCaret()
{
editBox.ScrollToCaret();
}
private void editBox_TextChanged(object sender, EventArgs e)
{
Invalidate();
}
}
public class RichTextBoxEx : System.Windows.Forms.RichTextBox
{
private double _Yfactor = 1.0d;
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, ref Point lParam);
private enum WindowsMessages
{
WM_USER = 0x400,
EM_GETSCROLLPOS = WM_USER + 221,
EM_SETSCROLLPOS = WM_USER + 222
}
public Point ScrollPos
{
get
{
var scrollPoint = new Point();
SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref scrollPoint);
return scrollPoint;
}
set
{
var original = value;
if (original.Y < 0)
original.Y = 0;
if (original.X < 0)
original.X = 0;
var factored = value;
factored.Y = (int)((double)original.Y * _Yfactor);
var result = value;
SendMessage(this.Handle, (int)WindowsMessages.EM_SETSCROLLPOS, 0, ref factored);
SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref result);
var loopcount = 0;
var maxloop = 100;
while (result.Y != original.Y)
{
// Adjust the input.
if (result.Y > original.Y)
factored.Y -= (result.Y - original.Y) / 2 - 1;
else if (result.Y < original.Y)
factored.Y += (original.Y - result.Y) / 2 + 1;
// test the new input.
SendMessage(this.Handle, (int)WindowsMessages.EM_SETSCROLLPOS, 0, ref factored);
SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref result);
// save new factor, test for exit.
loopcount++;
if (loopcount >= maxloop || result.Y == original.Y)
{
_Yfactor = (double)factored.Y / (double)original.Y;
break;
}
}
}
}
}
NumberedTextBox.Designer.cs
partial class NumberedTextBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.editBox = new WebTools.Controls.RichTextBoxEx();
this.SuspendLayout();
//
// editBox
//
this.editBox.AcceptsTab = true;
this.editBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.editBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.editBox.Location = new System.Drawing.Point(27, 3);
this.editBox.Name = "editBox";
this.editBox.ScrollPos = new System.Drawing.Point(0, 0);
this.editBox.Size = new System.Drawing.Size(120, 115);
this.editBox.TabIndex = 0;
this.editBox.Text = "";
this.editBox.WordWrap = false;
this.editBox.TextChanged += new System.EventHandler(this.editBox_TextChanged);
//
// NumberedTextBox
//
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Controls.Add(this.editBox);
this.Name = "NumberedTextBox";
this.Size = new System.Drawing.Size(150, 121);
this.ResumeLayout(false);
}
private RichTextBoxEx editBox;
#endregion
}

Related

Up and Down arrow Button in Windows forms C# visual studio 2019

enter image description hereenter image description here
Hello, Everyone I am trying to figure out a way to make the Exact replica of windows calculator, as a part of my C# learning assignment, I would like to know if there is any direct button in the tool box or any alternative way to get the up and down arrow , which will be used to move in the history of events entered by the user . which will be useful for him to recheck or edit easily. this question is totally related to windows forms UI (design)
You can use unicode triangles in the button's text property : ▲ ▼ and make the font bigger so that they're more visible, you can grab the triangles here: https://www.alt-codes.net/triangle-symbols.
If you want the exact same shape you'd have to make the image yourself in paint or just use snipping tool to save the arrows from your attached image. This can be set in the button's image property, remember to clear the text if you're using images.
Both can be set by right clicking the button in the designer and selecting properties.
one way to do that would be to subscribe to a KeyPress or KeyUp or KeyDown event of the control and check if the pressed key is up or down key and then run your logic.
this documentation might be helpful:
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress?view=net-5.0
I have grabbed out my very very old project and want to show you my implementation of a button that supports long press. It is quite a mess to only paint it but to get an idea:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace Teronis.Windows.Forms
{
public class TLongClickButton : Button
{
const int DEFAULT_LONG_CLICK_TIMER_TIME = 500; // milliseconds
const int DEFAULT_LONG_CLICK_TIMER_INTEVALL = 100; // milliseconds
/// <summary>
/// A static method for painting in OnPaint.
/// </summary>
/// <param name="btn"></param>
/// <param name="padding"></param>
/// <returns></returns>
public static Bitmap GetBitmap(Button btn, int padding = 2)
{
return new Bitmap(btn.ClientSize.Width - padding * 2, btn.ClientSize.Height - padding * 2);
}
public int LongClickTimerTime { get; set; } = DEFAULT_LONG_CLICK_TIMER_TIME;
public int LongClickTimerIntervall { get; set; } = DEFAULT_LONG_CLICK_TIMER_INTEVALL;
public bool LongClickSupport { get; set; } = false;
public EButtonDrawing ButtonDrawing { get; set; } = EButtonDrawing.Close;
public event EventHandler LongClick;
public event EventHandler ShortClick;
Bitmap bitmap;
Timer longClickTimer;
int milliseconds;
int padding = 2; // listbox border
bool isLongClick;
bool isMouseDown;
bool isLongClicking;
int activeLongClickTimerTime;
Size clientSize = Size.Empty;
public TLongClickButton()
{
Paint += TLongClickButton_Paint;
longClickTimer = new Timer();
longClickTimer.Tick += LongClickTimer_Tick;
}
private void TLongClickButton_Paint(object sender, PaintEventArgs e)
{
if (ClientSize.Width != clientSize.Width || ClientSize.Height != clientSize.Height) {
clientSize = ClientSize;
bitmap = GetBitmap(this, padding);
}
}
private void startTimer()
{
activeLongClickTimerTime = LongClickTimerTime;
longClickTimer.Interval = LongClickTimerIntervall;
longClickTimer.Start();
}
private void LongClickTimer_Tick(object sender, EventArgs e)
{
if (milliseconds < activeLongClickTimerTime)
milliseconds += longClickTimer.Interval;
else
isLongClick = true;
//
Invalidate();
}
protected override void WndProc(ref Message m)
{
if (m.Msg >= 0x0204 && m.Msg <= 0x020D)
return;
else
base.WndProc(ref m);
}
//protected override void OnClientSizeChanged(EventArgs e)
//{
// bitmap = GetBitmap(this, padding);
// base.OnClientSizeChanged(e);
//}
protected override void OnMouseDown(MouseEventArgs mevent)
{
if (LongClickSupport && mevent.Button == MouseButtons.Left) {
isMouseDown = true;
isLongClicking = true;
startTimer();
}
//
base.OnMouseDown(mevent);
}
protected override void OnMouseMove(MouseEventArgs mevent)
{
if (mevent.Button.HasFlag(MouseButtons.Left)) {
var isInClientArea = ClientRectangle.Contains(PointToClient(Cursor.Position));
if (isMouseDown && isLongClicking && !isInClientArea) {
longClickTimer.Stop();
isLongClicking = false;
milliseconds = 0;
isLongClick = false;
} else if (isMouseDown && !isLongClicking && isInClientArea) {
isLongClicking = true;
startTimer();
}
}
//
base.OnMouseMove(mevent);
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
//
isMouseDown = false;
}
protected override void OnMouseUp(MouseEventArgs mevent)
{
if (mevent.Button.HasFlag(MouseButtons.Left)) {
longClickTimer.Stop();
isLongClicking = false;
milliseconds = 0;
if (ClientRectangle.Contains(mevent.Location)) {
if (isLongClick)
LongClick?.Invoke(this, new EventArgs());
else
ShortClick?.Invoke(this, new EventArgs());
}
isLongClick = false;
}
//
base.OnMouseUp(mevent);
}
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
//
float filledArea = bitmap.Height * (float)milliseconds / LongClickTimerTime;
using (var graphics = Graphics.FromImage(bitmap)) {
graphics.Clear(SystemColors.Control);
graphics.FillRectangle(SystemBrushes.ControlDark, new Rectangle(0, 0, bitmap.Width, (int)filledArea));
var drawingPadding = padding + 2;
if (ButtonDrawing == EButtonDrawing.Close) {
var clientSize = new Size(ClientSize.Width - 1, ClientSize.Height - 1);
graphics.DrawLine(new Pen(Color.Black), Point.Add(Point.Empty, new Size(drawingPadding, drawingPadding)), Point.Subtract(new Point(clientSize.Width, clientSize.Height), new Size(drawingPadding * 2, drawingPadding * 2)));
graphics.DrawLine(new Pen(Color.Black), Point.Subtract(new Point(0, clientSize.Height), new Size(-drawingPadding, drawingPadding * 2)), Point.Add(new Point(clientSize.Width, 0), new Size(-drawingPadding * 2, drawingPadding)));
} else if (ButtonDrawing == EButtonDrawing.Settings) {
var horStep = (int)((bitmap.Height - padding * 2) / 9);
for (int i = 0; i < 3; i++) {
var horY = padding * 2 + (1 + i * 3) * horStep;
graphics.DrawLine(new Pen(Color.Black), new Point(padding, horY), new Point(bitmap.Width - padding * 2, horY));
}
} else if (ButtonDrawing == EButtonDrawing.Minimize) {
var horStep = (int)((bitmap.Height - padding * 2) / 9);
var horY = padding * 2 + (1 + 2 * 3) * horStep;
graphics.DrawLine(new Pen(Color.Black), new PointF(padding, horY), new PointF((int)((bitmap.Width - padding * 2) * 0.75f), horY));
} else if (ButtonDrawing == EButtonDrawing.Add) {
var innerPadding = 1;
var horYStep = (int)((bitmap.Height - padding * 2f) / 6);
var horY = padding * 2 + 2 * horYStep;
var newHorY = horY;
if (horY % 2 != 1)
newHorY -= 1;
var verXStep = (int)((bitmap.Width - padding * 2f) / 3);
var verX = padding * 2 + 1 * verXStep;
var newVerX = verX;
if (verX % 2 != 1)
newVerX -= 1;
graphics.DrawLine(new Pen(Color.Black), new Point(padding + innerPadding, newHorY), new Point((bitmap.Width - padding * 2) - innerPadding, newHorY));
graphics.DrawLine(new Pen(Color.Black), new Point(newVerX, padding + innerPadding), new Point(newVerX, (bitmap.Height - padding * 2) - innerPadding));
}
}
pevent.Graphics.DrawImageUnscaled(bitmap, padding, padding);
}
}
}

How to make Form Visible in C#

I am trying to design a piano for an assignment in C#. I have created a MusicKey class which stores music keys (as well as a BlackMusicKey class). I am populating the panel, 'panel1' with music keys like this:
this.panel1.Controls.Add(bmk);
In the music key constructor, I am setting a location and size for each music key, as well as ensuring that Visibility is set to true. However, when I run the form, it is completely blank.
Is there something that I am missing? I am quite sure that there is nothing wrong with the visibility of the music keys, so surely there is something that I am missing with regards to making the panel visible.
Any help will be appreciated, thanks!
Note: I have also tried using panel1.Show() which still did not work.
All relevant code can be found down below:
MusicKeyClass:
class MusKey : System.Windows.Forms.Button
{
private int musicNote; //determines the pitch mapped to number
public MusKey(int iNote, int x, int y) : base()
{
musicNote = iNote;
this.Location = new System.Drawing.Point(x, y);
this.Size = new System.Drawing.Size(20, 80);
this.Visible = true;
}
public int getMusicNote()
{
return musicNote;
}
}
Form1 Class:
public partial class Form1 : Form
{
int count = 0;
int xLoc = 50;
int yLoc = 30;
int[] whitePitch = { 1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22, 24 };
Panel panel1 = new Panel();
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
Button button1 = new Button();
private void Form1_Load(object sender, EventArgs e)
{
this.Paint += new PaintEventHandler(function);
MusKey mk;
BlackMusKey bmk;
for (int k = 0; k < 14; k++)
{
int pitch = whitePitch[k];
int ixPos = k * 20;
mk = new MusKey(pitch, ixPos, yLoc);
mk.MouseDown += new MouseEventHandler(this.button1_MouseDown);
mk.MouseUp += new MouseEventHandler(this.button1_MouseUp);
this.panel1.Controls.Add(mk);
}
int xOffs = 20;
int[] blackPitch = { 2, 4, 7, 9, 11, 14, 16, 19, 21, 23 };
int[] xPos = { 10, 30, 70, 110, 150, 170, 210, 230, 250 };
const int yPosBlack = 50;
for (int k = 0; k < 10; k++)
{
int pitch = blackPitch[k];
int ixPos = xPos[k];
bmk = new BlackMusKey(pitch, ixPos, yPosBlack);
bmk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown); //create event MouseDown
bmk.MouseUp += new System.Windows.Forms.MouseEventHandler(this.button1_MouseUp); //create event MouseUp
this.panel1.Controls.Add(bmk);
this.panel1.Controls[this.panel1.Controls.Count - 1].BringToFront();
}
}
SoundPlayer sp = new SoundPlayer();
int count1;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
foreach (MusKey mk in this.panel1.Controls)
{
if (sender == mk)
{ //true for the specific key pressed on the Music Keyboard
if (e.Button == MouseButtons.Left)
{
timer1.Enabled = true; //variable of the Timer component
count = 0; //incremented by the timer1_Tick event handler
timer1.Start();
sp.SoundLocation = (mk.getMusicNote() + ".wav"); //might need to convert ToString() ??
sp.Play();
}
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count = count++;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
foreach (MusKey mk in this.panel1.Controls)
{
if (sender == mk) //true for the specific key pressed on the Music Keyboard
{
if (e.Button == MouseButtons.Left)
{
timer1.Enabled = false;
sp.Stop();
string bNoteShape = null;
int duration = 0;
if (count >= 16)
{
bNoteShape = "SemiBreve";
duration = 16;
}
if (count >= 8 && count <= 15)
{
bNoteShape = "DotMinim";
duration = (8 + 15) / 2;
}
if (count >= 4 && count <= 7)
{
bNoteShape = "Crotchet";
duration = (4 + 7) / 2;
}
if (count >= 2 && count <= 3)
{
bNoteShape = "Quaver";
duration = (2 + 3) / 2;
}
if (count >= 1)
{
bNoteShape = "Semi-Quaver";
duration = 1;
}
MusicNote mn = new MusicNote(mk.getMusicNote(), duration, bNoteShape); //music note construction
// mn.Location = new Point(xLoc, yLoc);
//this.panel2.Controls.Add(this.mn); //adding MusicNote component to MusicStaff (panel2) collection
xLoc = xLoc + 15;
}
}
}
}
private void function(object sender, PaintEventArgs e)
{
panel1.Show();
panel1.Visible = true;
panel1.BackColor = Color.Blue;
panel1.Size = new Size(5, 5);
panel1.Location = new Point(3, 3);
this.Controls.Add(panel1);
this.Controls.Add(button1);
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
}
Form 1 [designer] Class:
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load_1);
this.ResumeLayout(false);
}
#endregion
}
Music Note Class
class MusicNote
{
public int notepitch;
public String noteshape;
public int noteduration;
enum accid { sharp, flat, sole };
bool dragging = false;
System.Timers.Timer timer1 = new System.Timers.Timer();
public MusicNote(int iNotepitch, int iDuration, String iBnoteShape)
{
notepitch = iNotepitch;
noteduration = iDuration;
noteshape = iBnoteShape;
}
bool timeron = false;
bool changenote = false;
public static int start = 0;
//public void click(object sender, MouseEventArgs e) { }
//public void RightPress(object sender, MouseEventArgs e) { }
}
}
Black Music Key Class
class BlackMusKey : MusKey
{
public BlackMusKey(int iNote, int x, int y) : base(iNote, x, y)
{
this.BackColor = Color.Black;
this.Size = new System.Drawing.Size(20, 60);
}
}
Program Class
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
According to Form1 class code, there is constructor missing. Please add proper constructor with InitializeComponent() method call. It can be added anywhere in class body.
Code snippet:
public partial class Form1 : Form
{
[...] //your objects declarations
public Form1()
{
InitializeComponent();
}
[...] //rest of your code
}

Programmatically created form is blank

I'm trying to create a pop up to notify users of a successful action. It is supposed to be visible for a couple seconds and fade away on its own. To do this, I've created a form that inherits from Form and sets the ShowWithoutActivation property to true, as well as a static class to control its construction and manipulate its opacity.
The problem is that when the new form is created, it has the correct size and initial opacity, but is completely blank. The only child control, a docked (Fill) label does not show. The Background/Foreground Color properties I set in the designer seem to be ignored in favor of default values as well. The Form fades and closes as intended.
The form itself:
public partial class TempForm : Form
{
protected override bool ShowWithoutActivation
{
get { return true; }
}
public TempForm(string message)
{
InitializeComponent();
messageLabel.Text = message;
}
private TempForm() { }
}
The static class that creates it:
public static class FadeAwayNotifier
{
public static void DisplayFadeNotification(Point parentLocation, string message)
{
Task t = Task.Factory.StartNew(() =>
{
int fadeDelay = 2000;
int animationLength = 1000;
int threadRestLength = 20;
Form popUp = buildForm(parentLocation, message);
popUp.Show();
int opacityIncrements = (animationLength / threadRestLength);
double opacityDecrementAmount = popUp.Opacity / opacityIncrements;
Thread.Sleep(fadeDelay);
for (int i = 0; i < opacityIncrements; i++)
{
Thread.Sleep(threadRestLength);
popUp.Opacity -= opacityDecrementAmount;
}
popUp.Close();
});
}
private static Form buildForm(Point startLocation, string text)
{
TempForm returnForm = new TempForm(text);
returnForm.Location = startLocation;
returnForm.messageLabel.Text = text;
returnForm.BackColor = Color.Black;
returnForm.ForeColor = Color.White;
return returnForm;
}
}
And, if it's helpful, here is the designer code for TempForm:
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.messageLabel = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// messageLabel
//
this.messageLabel.BackColor = System.Drawing.Color.Black;
this.messageLabel.Dock = System.Windows.Forms.DockStyle.Fill;
this.messageLabel.Font = new System.Drawing.Font("Cambria", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.messageLabel.ForeColor = System.Drawing.Color.White;
this.messageLabel.Location = new System.Drawing.Point(0, 0);
this.messageLabel.Name = "messageLabel";
this.messageLabel.Size = new System.Drawing.Size(254, 81);
this.messageLabel.TabIndex = 0;
this.messageLabel.Text = "Message";
this.messageLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// TempForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 19F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Black;
this.ClientSize = new System.Drawing.Size(254, 81);
this.Controls.Add(this.messageLabel);
this.Font = new System.Drawing.Font("Cambria", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.White;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "TempForm";
this.Opacity = 0.8D;
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "tempForm";
this.TopMost = true;
this.ResumeLayout(false);
}
#endregion
public System.Windows.Forms.Label messageLabel;
For those asking how the method is being called:
private void btnUpdate_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
/* Input validation here */
if (cmbBox.SelectedValue != null)
{
updateMethod(a, b....out errorMessage);
if (String.IsNullOrEmpty(errorMessage))
FadeAwayNotifier.DisplayFadeNotification(this.Location, "Rule successfully updated");
}
else
MessageBox.Show("A selection must be made in order to update");
Cursor.Current = Cursors.Default;
}
I've searched around but haven't seen anything that seemed to relate to the situation. I'm happy to be corrected if I missed something, though.
Why is the form that's created completely blank?
Your form is blank because you are trying to show it inside Task.Factory.StartNew().
Task.Factory.StartNew() runs code inside it asynchronous which is for some reason problem for form.Show() method.
Solution for this is to instead of Task t = Task.Factory.StartNew(... use Task t = new Tast(.... and then after you created task you run it with t.RunSynchronously(). This way it will work.
How i am displaying temp forms is:
Create temporary form create new blank winform (through vs solution explorer)
Add code like this:
public partial class TempForm : Form
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
double seconds = 3;
public TempForm(int secs, string text)
{
InitializeComponent();
//Custom property to dock it to down right to the screen
Rectangle workingArea = Screen.GetWorkingArea(this);
this.Location = new Point(workingArea.Right - Size.Width, workingArea.Bottom - Size.Height);
t = new System.Windows.Forms.Timer();
this.seconds = (secs != 0) ? secs : this.seconds;
richTextBox1.Text = text;
}
private void TempForm_Load(object sender, EventArgs e)
{
t.Interval = (int)(seconds * 1000);
t.Tick += new EventHandler(CloseForm);
t.Start();
}
private void CloseForm(object sender, EventArgs e)
{
this.Close();
this.Dispose();
}
public static void Show(int seconds, string text)
{
TempForm tf = new TempForm(seconds, text);
tf.Show();
}
}
To call it just use TempForm.Show(10, "SomeText");
Also make it look better (not like standard form) so it looks like this:

How can i make that when i run this application the main form will be in the taskbar bottom right corner?

I have downloaded the source code files from here of a magnifier glass effect:
http://www.codeproject.com/Articles/18235/Simple-Magnifier
And this is the main Form code:
///----------------------------------------------------------------------------
/// Class : MagnifierMainForm
/// Purpose : Provide simple magnifier.
/// Written by: Ogun TIGLI
/// History : 31 May 2006/Wed starting date.
/// 22 Dec 2006/Fri minor code fixes and hotsot support addition.
/// 01 Apr 2007/Sun XML serialization support added.
///
/// Notes:
/// This software is provided 'as-is', without any express or implied
/// warranty. In no event will the author be held liable for any damages
/// arising from the use of this software.
///
/// Permission is granted to anyone to use this software for any purpose,
/// including commercial applications, and to alter it and redistribute it
/// freely, subject to the following restrictions:
/// 1. The origin of this software must not be misrepresented;
/// you must not claim that you wrote the original software.
/// If you use this software in a product, an acknowledgment
/// in the product documentation would be appreciated.
/// 2. Altered source versions must be plainly marked as such, and
/// must not be misrepresented as being the original software.
/// 3. This notice cannot be removed, changed or altered from any source
/// code distribution.
///
/// (c) 2006-2007 Ogun TIGLI. All rights reserved.
///----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Magnifier20070401
{
public partial class MagnifierMainForm : Form
{
public MagnifierMainForm()
{
InitializeComponent();
GetConfiguration();
//--- My Init ---
FormBorderStyle = FormBorderStyle.None;
TopMost = true;
StartPosition = FormStartPosition.CenterScreen;
mImageMagnifierMainControlPanel = Properties.Resources.magControlPanel;
if (mImageMagnifierMainControlPanel == null)
throw new Exception("Resource cannot be found!");
Width = mImageMagnifierMainControlPanel.Width;
Height = mImageMagnifierMainControlPanel.Height;
HotSpot hsConfiguration = new HotSpot(new Rectangle(50, 15, 35, 30));
hsConfiguration.OnMouseDown += new HotSpot.MouseEventDelegate(hsConfiguration_OnMouseDown);
hsConfiguration.OnMouseUp += new HotSpot.MouseEventDelegate(hsConfiguration_OnMouseUp);
hsConfiguration.OnMouseMove += new HotSpot.MouseEventDelegate(hsConfiguration_OnMouseMove);
HotSpot hsMagnfier = new HotSpot(new Rectangle(10, 15, 30, 30));
hsMagnfier.OnMouseMove += new HotSpot.MouseEventDelegate(hsMagnfier_OnMouseMove);
hsMagnfier.OnMouseDown += new HotSpot.MouseEventDelegate(hsMagnfier_OnMouseDown);
hsMagnfier.OnMouseUp += new HotSpot.MouseEventDelegate(hsMagnfier_OnMouseUp);
HotSpot hsExit = new HotSpot(new Rectangle(95, 20, 15, 15));
hsExit.OnMouseUp += new HotSpot.MouseEventDelegate(hsExit_OnMouseUp);
mHotSpots.Add(hsConfiguration);
mHotSpots.Add(hsMagnfier);
mHotSpots.Add(hsExit);
ShowInTaskbar = false;
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
if (mConfiguration.LocationX != -1 && mConfiguration.LocationY != -1)
{
Location = new Point(mConfiguration.LocationX, mConfiguration.LocationY);
}
}
private string mConfigFileName = "configData.xml";
private void GetConfiguration()
{
try
{
mConfiguration = (Configuration)XmlUtility.Deserialize(mConfiguration.GetType(), mConfigFileName);
}
catch
{
mConfiguration = new Configuration();
}
}
private void SaveConfiguration()
{
try
{
XmlUtility.Serialize(mConfiguration, mConfigFileName);
}
catch (Exception e)
{
Console.WriteLine("Serialization problem: " + e.Message);
}
}
private void hsConfiguration_OnMouseMove(Object sender)
{
}
private void hsConfiguration_OnMouseUp(Object sender)
{
ConfigurationForm configForm = new ConfigurationForm(mConfiguration);
configForm.ShowDialog(this);
}
private void hsConfiguration_OnMouseDown(Object sender)
{
}
private void hsMagnfier_OnMouseUp(object sender)
{
}
private void hsMagnfier_OnMouseDown(object sender)
{
int x = mLastCursorPosition.X;
int y = mLastCursorPosition.Y;
MagnifierForm magnifier = new MagnifierForm(mConfiguration, mLastCursorPosition);
magnifier.Show();
}
private void hsMagnfier_OnMouseMove(object sender)
{
}
private void hsExit_OnMouseUp(Object sender)
{
SaveConfiguration();
Application.Exit();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
if (mImageMagnifierMainControlPanel != null)
{
g.DrawImage(mImageMagnifierMainControlPanel, 0, 0, Width, Height);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
int x = e.X;
int y = e.Y;
mPointMouseDown = new Point(e.X, e.Y);
mLastCursorPosition = Cursor.Position;
foreach (HotSpot hotSpot in mHotSpots)
{
// If mouse event handled by this hot-stop then return!
if (hotSpot.ProcessMouseDown(e)) return;
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
foreach (HotSpot hotSpot in mHotSpots)
{
// If mouse event handled by this hot-stop then return!
if (hotSpot.ProcessMouseUp(e)) return;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
foreach (HotSpot hotSpot in mHotSpots)
{
// If mouse event handled by this hot-stop then return!
if (hotSpot.ProcessMouseMove(e))
{
Cursor = Cursors.Hand;
return;
}
}
Cursor = Cursors.SizeAll;
if (e.Button == MouseButtons.Left)
{
int dx = e.X - mPointMouseDown.X;
int dy = e.Y - mPointMouseDown.Y;
Left += dx;
Top += dy;
mConfiguration.LocationX = Left;
mConfiguration.LocationY = Top;
}
}
private Image mImageMagnifierMainControlPanel = null;
private List<HotSpot> mHotSpots = new List<HotSpot>();
private Point mPointMouseDown;
private Point mLastCursorPosition;
private Configuration mConfiguration = new Configuration();
}
}
I tried to change this line: StartPosition = FormStartPosition.CenterScreen; but what ever i change it to it doesn't change or make any effects.
I want that instead it will show the form in the center of the screen it will be in the bottom right corner or on the bottom left side with all programs in the taskbar.
How can i do it ? Tried so many things but this line dosen't make any changes.
Found it. This line change the location:
if (mConfiguration.LocationX != -1 && mConfiguration.LocationY != -1)
{
Location = new Point(0,0);//mConfiguration.LocationX, mConfiguration.LocationY);
}
For the example 0 ,0 change the form location ot the top left corner.
Thanks.
You could try with something like this:
Form f1 = new Form();
f1.StartPosition = FormStartPosition.Manual;
f1.Left = Screen.PrimaryScreen.WorkingArea.Width - f1.Width;
f1.Top = Screen.PrimaryScreen.WorkingArea.Height - f1.Height;
f1.Show();

How to capture SDI windows image when it is minimize in MDI form c# win apps

in windows 7 one feature is very good that when any apps is minimize and when user point mouse cursor on that minimize for then the image of that form is show in hover popup. so if i want to do it in my MDI form that when any SDI is minimize in MDI form and when user point mouse on that minimize form then the form image will show in hover popup. how to accomplish it in windows application through c#
I have not tried this my self, but if I would think that the most likely solution for an MDI application would be to create the bitmap image of the child window prior to it being minimized and then use that image to show the last state of the window.
You will also need to handle a few of the 'WM_NC*' messages to detect that the mouse is hovering over the minimized window and then render your cached image in a popup.
UPDATE:
Here is a quick and dirty proof of concept, it is not perfect the tooltip does not follow all the standard tooltip functionality etc. but it should be enough to get you started. The code could also be refactored to be more reusable, but at this stage you could derive your MDI child windows from this MDIChild and you would have this basic tooltip functionality. Of course there will be issues if windows are overlapping etc.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MDITest
{
public partial class MDIChild : Form
{
private static TooltipForm _tooltip = new TooltipForm();
private static Form _lastForm;
private Image _lastSnapshot;
public MDIChild()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_COMMAND && m.WParam.ToInt32() == SC_MINIMIZE)
{
OnMinimize(EventArgs.Empty);
}
else if (m.Msg == WM_NCMOUSEMOVE)
{
int x = m.LParam.ToInt32() & 0x0000ffff;
int y = m.LParam.ToInt32() >> 16;
OnNcMouseMove(new MouseEventArgs(MouseButtons.None, 0, x, y, 0));
}
base.WndProc(ref m);
}
protected virtual void OnNcMouseMove(MouseEventArgs e)
{
if (this.WindowState == FormWindowState.Minimized && _lastForm != this)
{
_lastForm = this;
Point pt = MdiParent.PointToScreen(this.Location);
ShowWindowTip(pt, _lastSnapshot);
}
}
protected virtual void OnMinimize(EventArgs e)
{
_tooltip.Visible = false;
if (_lastSnapshot == null)
{
_lastSnapshot = new Bitmap(100, 100);
}
using (Image windowImage = new Bitmap(ClientRectangle.Width, ClientRectangle.Height))
using (Graphics windowGraphics = Graphics.FromImage(windowImage))
using (Graphics tipGraphics = Graphics.FromImage(_lastSnapshot))
{
Rectangle r = this.RectangleToScreen(ClientRectangle);
windowGraphics.CopyFromScreen(new Point(r.Left, r.Top), Point.Empty, new Size(r.Width, r.Height));
windowGraphics.Flush();
float scaleX = 1;
float scaleY = 1;
if (ClientRectangle.Width > ClientRectangle.Height)
{
scaleY = (float)ClientRectangle.Height / ClientRectangle.Width;
}
else if (ClientRectangle.Height > ClientRectangle.Width)
{
scaleX = (float)ClientRectangle.Width / ClientRectangle.Height;
}
tipGraphics.DrawImage(windowImage, 0, 0, 100 * scaleX, 100 * scaleY);
}
}
private static void ShowWindowTip(Point pt, Image image)
{
if (_tooltip.Visible)
{
_tooltip.Visible = false;
}
_tooltip.Image = image;
_tooltip.Show();
_tooltip.Location = new Point(pt.X, pt.Y - _tooltip.Height - 10);
}
private static int WM_NCMOUSEMOVE = 0x00A0;
private static int WM_COMMAND = 0x0112;
private static int SC_MINIMIZE = 0xf020;
}
}
Here is the TooltipForm.designer.cs
namespace MDITest
{
partial class TooltipForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(134, 112);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// TooltipForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(134, 112);
this.ControlBox = false;
this.Controls.Add(this.pictureBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "TooltipForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "TooltipForm";
this.TopMost = true;
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
}
}
And the TooltipForm.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MDITest
{
public partial class TooltipForm : Form
{
Timer _timer = new Timer();
public TooltipForm()
{
InitializeComponent();
TopLevel = true;
_timer.Enabled = false;
_timer.Interval = 5000;
_timer.Tick += new EventHandler(_timer_Tick);
}
void _timer_Tick(object sender, EventArgs e)
{
Visible = false;
}
protected override void SetVisibleCore(bool value)
{
if (value == true)
{
_timer.Start();
}
else
{
_timer.Stop();
}
base.SetVisibleCore(value);
}
public Image Image
{
get
{
return pictureBox1.Image;
}
set
{
pictureBox1.Image = value;
}
}
}
}

Categories

Resources