Related
I am using MonoDevelop IDE on linux/UNIX machine and coding in C# and .NET framework. I cannot seem to figure out how to get the Gtk::DrawingArea to show up in the parent Gtk.Window when the project builds?
I have tried adding a ::drawingArea object manually into the Code, placing it directly on the window (in the design view, see screenshot) and then I also tried placing the ::drawingArea object within a Fixed box.
Below is the code that I am trying to implement. The Design is as basic as you can get, just so I can understand catching and working with the signals to the drawingArea - it has the parent window (MainWindow) and the drawing area (drawingarea1).
Screenshot
My question: How can I get a drawingArea object to display in a Gtk.Window? And, more importantly is there something I am missing to make the object respond to signals that are set to the drawingarea? I want to ultimately be able to draw and color inside the drawing area window but as of right now I can't even get the drawing area widget to display and catch signals.
Thanks in advance!
MainWidow.cs
using System;
using Gtk;
public partial class MainWindow : Gtk.Window
{
public DrawingArea d;
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
d = drawingarea1;
Build();
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
protected void OnExpose(object o, ExposeEventArgs args)
{
Console.WriteLine("OnExpose...");
}
protected void OnRealization(object sender, EventArgs e)
{
Console.WriteLine("OnRealization...");
}
protected void OnDragMotion(object o, DragMotionArgs args)
{
Console.WriteLine("OnDragMotion...");
}
}
Driver.cs
using System;
using Gtk;
class MainClass
{
public static void Main(string[] args)
{
Application.Init();
MainWindow win = new MainWindow();
// throws NULLREFERENCE EXECPTION
win.d.Show();
win.Show();
Application.Run();
}
}
//******* PARTIAL SOLUTION **********//
ColorSelectorDraw.cs
using System;
using Gtk;
using Gdk;
namespace GUIDraw4
{
public class DemoColorSelection : Gtk.Window
{
private Gdk.Color color;
private Gtk.DrawingArea drawingArea;
public DemoColorSelection() : base("Color Selection")
{
BorderWidth = 8;
VBox vbox = new VBox(false, 8);
vbox.BorderWidth = 8;
Add(vbox);
// Create the color swatch area
Frame frame = new Frame();
frame.ShadowType = ShadowType.In;
vbox.PackStart(frame, true, true, 0);
drawingArea = new DrawingArea();
drawingArea.ExposeEvent += new ExposeEventHandler(ExposeEventCallback);
// set a minimum size
drawingArea.SetSizeRequest(400, 250);
// set the color
color = new Gdk.Color(255, 255, 255);
drawingArea.ModifyBg(StateType.Normal, color);
frame.Add(drawingArea);
Alignment alignment = new Alignment(1.0f, 0.5f, 0.0f, 0.0f);
Button button = new Button("_Change the above color");
button.Clicked += new EventHandler(ChangeColorCallback);
alignment.Add(button);
vbox.PackStart(alignment);
ShowAll();
}
protected override bool OnDeleteEvent(Gdk.Event evt)
{
Destroy();
return true;
}
// Expose callback for the drawing area
private void ExposeEventCallback(object o, ExposeEventArgs args)
{
EventExpose eventExpose = args.Event;
Gdk.Window window = eventExpose.Window;
Rectangle area = eventExpose.Area;
window.DrawRectangle(drawingArea.Style.BackgroundGC(StateType.Normal),
true,
area.X, area.Y,
area.Width, area.Height);
args.RetVal = true;
}
private void ChangeColorCallback(object o, EventArgs args)
{
using (ColorSelectionDialog colorSelectionDialog = new ColorSelectionDialog("Changing color"))
{
colorSelectionDialog.TransientFor = this;
colorSelectionDialog.ColorSelection.PreviousColor = color;
colorSelectionDialog.ColorSelection.CurrentColor = color;
colorSelectionDialog.ColorSelection.HasPalette = true;
if (colorSelectionDialog.Run() == (int)ResponseType.Ok)
{
Gdk.Color selected = colorSelectionDialog.ColorSelection.CurrentColor;
drawingArea.ModifyBg(StateType.Normal, selected);
}
colorSelectionDialog.Hide();
}
}
}
}
Program.cs
using System;
using Gtk;
namespace GUIDraw4
{
class MainClass
{
public static void Main(string[] args)
{
Application.Init();
//MainWindow win = new MainWindow();
//win.Show();
DemoColorSelection cs = new DemoColorSelection();
Application.Run();
}
}
}
This seemed to at least get an interactive drawing board up on the GUI. Taken from csharp.hotexamples.com
I am trying to write something along of a "clean" code... I want to make a Pong game, for now based on Forms.
I want to divide the game nicely into classes.
I want to have a ball class, AI that inherits from player class, I want to use the premade Form class for setting main Form properties (width etc).
I made a player class as such and I would like to ask you if the approach for naming, getters and setters and the general idea is correct. Isn't certain bits (if not all of it) rather redundant or badly written, I do not want to base entire "project" on bad assumptions and multiply the same mistakes all over the code.
namespace Pong
{
public class Player
{
protected PictureBox PaddleBox { get; set; }
protected Size PlayerSize
{
get
{
return PlayerSize;
}
set
{
if (PlayerSize.Height > 0 && PlayerSize.Width > 0)
{
PlayerSize = new Size(value.Width, value.Height);
PaddleBox.Size = PlayerSize;
}
}
}
protected Point Location
{
get
{
return Location;
}
set
{
PaddleBox.Location = new Point(value.X, value.Y);
}
}
protected Color BackColor
{
get
{
return BackColor;
}
set
{
PaddleBox.BackColor = value;
}
}
public Player()
{
PaddleBox = new PictureBox();
}
}
}
FORM class looks something along of this for now, maybe I should pass parameters such as size,location and color in the constructor? What is the best?
namespace Pong
{
public partial class Form1 : Form
{
public Timer gameTime;
const int screenWidth = 1248;
const int screenHeight = 720;
public Form1()
{
InitializeComponent();
this.Height= screenHeight;
this.Width=screenWidth;
this.StartPosition=FormStartPosition.CenterScreen;
Player player = new Player();
player.PaddleBox.Size = new Size(20, 50);
player.PaddleBox.Location = new Point(player.PaddleBox.Width / 2, ClientSize.Height/2-player.PaddleBox.Height/2);
player.PaddleBox.BackColor = Color.Blue;
this.Controls.Add(player.PaddleBox);
gameTime = new Timer();
gameTime.Enabled = true;
}
void gameTime_Tick(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You got an issue here:
protected Point Location
{
get
{
return Location; // <--- this is a circular reference..
// meaning, it will recall this getter again.
}
set
{
PaddleBox.Location = new Point(value.X, value.Y);
}
}
use this instead:
protected Point Location
{
get
{
return PaddleBox.Location;
}
set
{
PaddleBox.Location = value;
}
}
Same with protected Color BackColor
Here is an example, how I would implement it (in your current programming style (powered by notepad))
namespace Pong
{
public partial class Form1 : Form
{
public Timer gameTime;
const int screenWidth = 1248;
const int screenHeight = 720;
public Form1()
{
InitializeComponent();
this.Height= screenHeight;
this.Width=screenWidth;
this.StartPosition=FormStartPosition.CenterScreen;
Player player = new Player(this);
player.PlayerSize = new Size(20, 50);
player.Location = new Point(player.PaddleBox.Width / 2, ClientSize.Height/2-player.PaddleBox.Height/2); // <-- the location is always the upperleft point. don't do this...
player.BackColor = Color.Blue;
gameTime = new Timer();
gameTime.Enabled = true;
}
private void gameTime_Tick(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class Player
{
private PictureBox _paddleBox;
protected Size PlayerSize
{
get
{
return _paddleBox.Size;
}
set
{
if (PlayerSize.Height == 0 || PlayerSize.Width == 0)
throw new ArgumentException("Size must be greater than 0");
_paddleBox.Size = value;
}
}
protected Point Location
{
get { return PaddleBox.Location; }
set { PaddleBox.Location = value; }
}
protected Color BackColor
{
get { return PaddleBox.BackColor; }
set { PaddleBox.BackColor = value; }
}
public Player(Form form)
{
PaddleBox = new PictureBox();
form.Controls.Add(PaddleBox);
}
}
}
You should try to isolate the picturebox in your player class, this will separate the functionality of the form and the picturebox...
Can anyone point me to a good implementation of a basic Windows Forms TextBox that will initially show watermark text that disappears when the cursor enters it? I think I can create my own with some creative use of Enter and Leave events, but I'm sure there's a perfectly usable implementation sitting around somewhere. I saw the WPF implementation and if necessary I could nest it, but a native WinForms TextBox derivative would be better.
I have this so far; haven't tried it yet but does anyone see any glaring problems?
public class WatermarkTextBox:TextBox
{
public string WatermarkText { get; set; }
public Color WatermarkColor { get; set; }
private Color TextColor { get; set; }
private bool isInTransition;
public WatermarkTextBox()
{
WatermarkColor = SystemColors.GrayText;
}
private bool HasText { get { return Text.IsNotNullOrBlankOr(WatermarkText); }}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
if (HasText) return;
isInTransition = true;
ForeColor = TextColor;
Text = String.Empty;
isInTransition = false;
}
protected override void OnForeColorChanged(EventArgs e)
{
base.OnForeColorChanged(e);
if (!isInTransition) //the change came from outside
TextColor = ForeColor;
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
if (HasText) return;
isInTransition = true;
ForeColor = WatermarkColor;
Text = WatermarkText.EmptyIfNull();
isInTransition = false;
}
}
EDIT: The above would have eventually worked with some finessing, but the CueProvider worked much better. Here's my final implementation:
public class WatermarkTextBox:TextBox
{
private string watermarkText;
public string WatermarkText
{
get { return watermarkText; }
set
{
watermarkText = value;
if (watermarkText.IsNullOrBlank())
CueProvider.ClearCue(this);
else
CueProvider.SetCue(this, watermarkText);
}
}
}
I could have integrated the CueProvider functionality completely, but this works beautifully.
The official term is "cue banner". Here's another way to do it, just inheriting TextBox gets the job done too. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox and set the Cue property.
You get a live preview of the Cue value in the designer, localized to the form's Language property. Lots of bang for very little buck, an excellent demonstration of the good parts of Winforms.
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
class CueTextBox : TextBox {
[Localizable(true)]
public string Cue {
get { return mCue; }
set { mCue = value; updateCue(); }
}
private void updateCue() {
if (this.IsHandleCreated && mCue != null) {
SendMessage(this.Handle, 0x1501, (IntPtr)1, mCue);
}
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
updateCue();
}
private string mCue;
// PInvoke
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, string lp);
}
I've updated the answer given by #Hans Passant above to introduce constants, make it consistent with pinvoke.net definitions and to let the code pass FxCop validation.
class CueTextBox : TextBox
{
private static class NativeMethods
{
private const uint ECM_FIRST = 0x1500;
internal const uint EM_SETCUEBANNER = ECM_FIRST + 1;
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, string lParam);
}
private string _cue;
public string Cue
{
get
{
return _cue;
}
set
{
_cue = value;
UpdateCue();
}
}
private void UpdateCue()
{
if (IsHandleCreated && _cue != null)
{
NativeMethods.SendMessage(Handle, NativeMethods.EM_SETCUEBANNER, (IntPtr)1, _cue);
}
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
UpdateCue();
}
}
Edit: update the PInvoke call to set CharSet attribute, to err on the safe side. For more info see the SendMessage page at pinvoke.net.
.NET 5.0+, .NET Core 3.0+
You can use PlaceholderText property. It supports both multi-line and single-line text-box.
textBox1.PlaceholderText = "Something";
If you look into the .NET CORE implementation of TextBox you see it's been implemented by handling paint message.
.NET Framework
Here is an implementation of a TextBox which supports showing hint (or watermark or cue):
It also shows the hint when MultiLine is true.
It's based on handling WM_PAINT message and drawing the hint. So you can simply customize the hint and add some properties like hint color, or you can draw it right to left or control when to show the hint.
using System.Drawing;
using System.Windows.Forms;
public class ExTextBox : TextBox
{
string hint;
public string Hint
{
get { return hint; }
set { hint = value; this.Invalidate(); }
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0xf)
{
if (!this.Focused && string.IsNullOrEmpty(this.Text)
&& !string.IsNullOrEmpty(this.Hint))
{
using (var g = this.CreateGraphics())
{
TextRenderer.DrawText(g, this.Hint, this.Font,
this.ClientRectangle, SystemColors.GrayText , this.BackColor,
TextFormatFlags.Top | TextFormatFlags.Left);
}
}
}
}
}
If you use EM_SETCUEBANNER, then there will be 2 issues. The text always will be shown in a system default color. Also the text will not be shown when the TextBox is MultiLine.
Using the painting solution, you can show the text with any color that you want. You also can show the watermark when the control is multi-line:
Download
You can clone or download the working example:
Download Zip
Github repository
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
And the message constants:
private const uint EM_SETCUEBANNER = 0x1501;
private const uint CB_SETCUEBANNER = 0x1703; // minimum supported client Windows Vista, minimum supported server Windows Server 2008
And imho the best way to implement it is as an extension method.
So for the TextBox control the syntax would be:
MyTextBox.CueBanner(false, "Password");
From the code:
public static void CueBanner(this TextBox textbox, bool showcuewhenfocus, string cuetext)
{
uint BOOL = 0;
if (showcuewhenfocus == true) { BOOL = 1; }
SendMessage(textbox.Handle, EM_SETCUEBANNER, (IntPtr)BOOL, cuetext); ;
}
Using WinForms on .NET Core:
This has been greatly simplified in .NET Core. You can directly add placeholder text by modifying the new PlaceholderText Property of the TextBox.
public virtual string PlaceholderText { get; set; }
Note that you would probably still have to edit the ForeColor if you want to get a colored Placeholder Text. The PlaceholderText field is visible when the Text field is null or empty.
You can add a watermark to a Textbox (multiline or not) that works pretty well by drawing it in different controls Paint event. For Example:
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
If TextBox1.Text = "" Then
TextBox1.CreateGraphics.DrawString("Enter Text Here", Me.Font, New SolidBrush(Color.LightGray), 0, 0)
End If
End Sub
-OO-
I wrote a reusable custom control class for my project.
maybe it can help someone that need to implement multiple placeholder textboxes in his project.
here is the C# and vb.net versions:
C#:
namespace reusebleplaceholdertextbox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// implementation
CustomPlaceHolderTextbox myCustomTxt = new CustomPlaceHolderTextbox(
"Please Write Text Here...", Color.Gray, new Font("ARIAL", 11, FontStyle.Italic)
, Color.Black, new Font("ARIAL", 11, FontStyle.Regular)
);
myCustomTxt.Multiline = true;
myCustomTxt.Size = new Size(200, 50);
myCustomTxt.Location = new Point(10, 10);
this.Controls.Add(myCustomTxt);
}
}
class CustomPlaceHolderTextbox : System.Windows.Forms.TextBox
{
public string PlaceholderText { get; private set; }
public Color PlaceholderForeColor { get; private set; }
public Font PlaceholderFont { get; private set; }
public Color TextForeColor { get; private set; }
public Font TextFont { get; private set; }
public CustomPlaceHolderTextbox(string placeholdertext, Color placeholderforecolor,
Font placeholderfont, Color textforecolor, Font textfont)
{
this.PlaceholderText = placeholdertext;
this.PlaceholderFont = placeholderfont;
this.PlaceholderForeColor = placeholderforecolor;
this.PlaceholderFont = placeholderfont;
this.TextForeColor = textforecolor;
this.TextFont = textfont;
if (!string.IsNullOrEmpty(this.PlaceholderText))
{
SetPlaceHolder(true);
this.Update();
}
}
private void SetPlaceHolder(bool addEvents)
{
if (addEvents)
{
this.LostFocus += txt_lostfocus;
this.Click += txt_click;
}
this.Text = PlaceholderText;
this.ForeColor = PlaceholderForeColor;
this.Font = PlaceholderFont;
}
private void txt_click(object sender, EventArgs e)
{
// IsNotFirstClickOnThis:
// if there is no other control in the form
// we will have a problem after the first load
// because we dont other focusable control to move the focus to
// and we dont want to remove the place holder
// only on first time the place holder will be removed by click event
RemovePlaceHolder();
this.GotFocus += txt_focus;
// no need for this event listener now
this.Click -= txt_click;
}
private void RemovePlaceHolder()
{
this.Text = "";
this.ForeColor = TextForeColor;
this.Font = TextFont;
}
private void txt_lostfocus(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.Text))
{
// set placeholder again
SetPlaceHolder(false);
}
}
private void txt_focus(object sender, EventArgs e)
{
if (this.Text == PlaceholderText)
{
// IsNotFirstClickOnThis:
// if there is no other control in the form
// we will have a problem after the first load
// because we dont other focusable control to move the focus to
// and we dont want to remove the place holder
RemovePlaceHolder();
}
}
}
}
VB.NET:
Namespace CustomControls
Public Class PlaceHolderTextBox
Inherits System.Windows.Forms.TextBox
Public Property PlaceholderText As String
Public Property PlaceholderForeColor As Color
Public Property PlaceholderFont As Font
Public Property TextForeColor As Color
Public Property TextFont As Font
Public Sub New(ByVal placeholdertext As String, ByVal placeholderforecolor As Color, ByVal placeholderfont As Font, ByVal txtboxbackcolor As Color, ByVal textforecolor As Color, ByVal textfont As Font)
Me.PlaceholderText = placeholdertext
Me.PlaceholderFont = placeholderfont
Me.PlaceholderForeColor = placeholderforecolor
Me.PlaceholderFont = placeholderfont
Me.TextForeColor = textforecolor
Me.TextFont = textfont
Me.BackColor = txtboxbackcolor
If Not String.IsNullOrEmpty(Me.PlaceholderText) Then
SetPlaceHolder(True)
Me.Update()
End If
End Sub
Private Sub SetPlaceHolder(ByVal addEvents As Boolean)
If addEvents Then
AddHandler Me.LostFocus, AddressOf txt_lostfocus
AddHandler Me.Click, AddressOf txt_click
End If
Me.Text = PlaceholderText
Me.ForeColor = PlaceholderForeColor
Me.Font = PlaceholderFont
End Sub
Private Sub txt_click(ByVal sender As Object, ByVal e As EventArgs)
RemovePlaceHolder()
AddHandler Me.GotFocus, AddressOf txt_focus
RemoveHandler Me.Click, AddressOf txt_click
End Sub
Private Sub RemovePlaceHolder()
Me.Text = ""
Me.ForeColor = TextForeColor
Me.Font = TextFont
End Sub
Private Sub txt_lostfocus(ByVal sender As Object, ByVal e As EventArgs)
If String.IsNullOrEmpty(Me.Text) Then
SetPlaceHolder(False)
End If
End Sub
Private Sub txt_focus(ByVal sender As Object, ByVal e As EventArgs)
If Me.Text = PlaceholderText Then
RemovePlaceHolder()
End If
End Sub
End Class
End Namespace
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace PlaceHolderTextBoxCSharp
{
public class CTextBox : TextBox
{
private Panel contenedor;
protected string texto = "PlaceHolderText";
protected Color colorTextoDefault = Color.Gray;
public Color colorTexto = Color.Gray;
protected Color colorTextoObligatorio = Color.Red;
private Font fuente;
private SolidBrush establecerColorTexto;
private bool obligatoriedad = false;
private bool colorConFoco = false;
private int vuelta = 0;
public CTextBox()
{
Inicializar();
}
private void Inicializar()
{
fuente = Font;
CharacterCasing = CharacterCasing.Upper;
contenedor = null;
MuestraPlaceHolder();
Leave += new EventHandler(PierdeFoco);
TextChanged += new EventHandler(CambiaTexto);
}
private void EliminaPlaceHolder()
{
if (contenedor != null)
{
Controls.Remove(contenedor);
contenedor = null;
}
}
private void MuestraPlaceHolder()
{
if (contenedor == null && TextLength <= 0)
{
contenedor = new Panel();
contenedor.Paint += new PaintEventHandler(contenedorPaint);
contenedor.Invalidate();
contenedor.Click += new EventHandler(contenedorClick);
Controls.Add(contenedor);
}
}
private void contenedorClick(object sender, EventArgs e)
{
Focus();
}
private void contenedorPaint(object sender, PaintEventArgs e)
{
contenedor.Location = new Point(2, 0);
contenedor.Height = Height;
contenedor.Width = Width;
contenedor.Anchor = AnchorStyles.Left | AnchorStyles.Right;
establecerColorTexto = new SolidBrush(colorTexto);
Graphics g = e.Graphics;
g.DrawString(texto, fuente, establecerColorTexto, new PointF(-1f, 1f));
}
private void PierdeFoco(object sender, EventArgs e)
{
if (TextLength > 0)
{
EliminaPlaceHolder();
}
else
{
if (obligatoriedad == true)
{
colorTexto = colorTextoObligatorio;
}
else
{
colorTexto = colorTextoDefault;
}
Invalidate();
}
}
private void CambiaTexto(object sender, EventArgs e)
{
if (TextLength > 0)
{
EliminaPlaceHolder();
}
else
{
MuestraPlaceHolder();
vuelta += 1;
if (vuelta >= 1 && obligatoriedad == true)
{
colorTexto = colorTextoObligatorio;
}
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
MuestraPlaceHolder();
}
protected override void OnInvalidated(InvalidateEventArgs e)
{
base.OnInvalidated(e);
if (contenedor != null)
{
contenedor.Invalidate();
}
}
[Category("Atributos PlaceHolder")]
[Description("Establece el texto a mostrar.")]
public string PlaceHolderText
{
get
{
return texto;
}
set
{
texto = value;
Invalidate();
}
}
[Category("Atributos PlaceHolder")]
[Description("Establece el estilo de fuente del PlaceHolder.")]
public Font PlaceHolderFont
{
get
{
return fuente;
}
set
{
fuente = value;
Invalidate();
}
}
[Category("Atributos PlaceHolder")]
[Description("Indica si el campo es obligatorio.")]
public bool PlaceHolderFieldRequired
{
get
{
return obligatoriedad;
}
set
{
obligatoriedad = value;
Invalidate();
}
}
}
}
With .Net Core 3 a property was introduced into TextBox: PlaceHolderText
If one is going to need this in a FrameWork application the required code parts can be taken from the official open source code and placed in a TextBox descendant (see license).
This supports multiline TextBox and also RTL text.
public class PlaceHolderTextBox : TextBox
{
private const int WM_KILLFOCUS = 0x0008;
private const int WM_PAINT = 0x000F;
private string _placeholderText;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (this.ShouldRenderPlaceHolderText(m))
{
using Graphics g = this.CreateGraphics();
this.DrawPlaceholderText(g);
}
}
#region PlaceHolder
/// <summary>
/// Gets or sets the text that is displayed when the control has no text and does not have the focus.
/// </summary>
/// <value>The text that is displayed when the control has no text and does not have the focus.</value>
[Localizable(true), DefaultValue("")]
public virtual string PlaceholderText
{
get => _placeholderText;
set
{
if (value == null)
{
value = string.Empty;
}
if (_placeholderText != value)
{
_placeholderText = value;
if (this.IsHandleCreated)
{
this.Invalidate();
}
}
}
}
//-------------------------------------------------------------------------------------------------
/// <summary>
/// Draws the <see cref="PlaceholderText"/> in the client area of the <see cref="TextBox"/> using the default font and color.
/// </summary>
private void DrawPlaceholderText(Graphics graphics)
{
TextFormatFlags flags = TextFormatFlags.NoPadding | TextFormatFlags.Top |
TextFormatFlags.EndEllipsis;
Rectangle rectangle = this.ClientRectangle;
if (this.RightToLeft == RightToLeft.Yes)
{
flags |= TextFormatFlags.RightToLeft;
switch (this.TextAlign)
{
case HorizontalAlignment.Center:
flags |= TextFormatFlags.HorizontalCenter;
rectangle.Offset(0, 1);
break;
case HorizontalAlignment.Left:
flags |= TextFormatFlags.Right;
rectangle.Offset(1, 1);
break;
case HorizontalAlignment.Right:
flags |= TextFormatFlags.Left;
rectangle.Offset(0, 1);
break;
}
}
else
{
flags &= ~TextFormatFlags.RightToLeft;
switch (this.TextAlign)
{
case HorizontalAlignment.Center:
flags |= TextFormatFlags.HorizontalCenter;
rectangle.Offset(0, 1);
break;
case HorizontalAlignment.Left:
flags |= TextFormatFlags.Left;
rectangle.Offset(1, 1);
break;
case HorizontalAlignment.Right:
flags |= TextFormatFlags.Right;
rectangle.Offset(0, 1);
break;
}
}
TextRenderer.DrawText(graphics, this.PlaceholderText, this.Font, rectangle, SystemColors.GrayText, this.BackColor, flags);
}
private bool ShouldRenderPlaceHolderText(in Message m) =>
!string.IsNullOrEmpty(this.PlaceholderText) &&
(m.Msg == WM_PAINT || m.Msg == WM_KILLFOCUS) &&
!this.GetStyle(ControlStyles.UserPaint) &&
!this.Focused && this.TextLength == 0;
#endregion
}
Update 30/12/2022
With .NET6 (or maybe lower version have this option, I'm not sure)
Just right-click on textbox > properties > PlaceHolderText > and set it as anything you want
click here to see that property in picture
Private Sub randomSubName() Handles txtWatermark.Click
txtWatermark.text = ""
End Sub
Make the default text of the textbox whatever you want the watermark to be, I assume in this example you name the textbox txtWatermark
Hey, I'm new. So sorry if I terribly screwed up the post... I also have no idea if this works...
I am showing a little tooltip, but if I change the selecteditem/text in the dropdownmenu, tooltip shows the old text and the new text. I want it to show only the new text.
private void optionsvalueComboBox_MouseHover(object sender, EventArgs e)
{
ToolTip buttonToolTip = new ToolTip();
buttonToolTip.ToolTipTitle = "Value";
buttonToolTip.UseFading = true;
buttonToolTip.UseAnimation = true;
buttonToolTip.IsBalloon = true;
buttonToolTip.ShowAlways = true;
buttonToolTip.AutoPopDelay = 5000;
buttonToolTip.InitialDelay = 1000;
buttonToolTip.ReshowDelay = 0;
buttonToolTip.SetToolTip(optionsvalueComboBox, optionsvalueComboBox.Text);
}
Assuming what you don't like is the tooltip text changing from the old text to the new text...
The reason it's doing that is because you are creating a new tooltip instance on every hover event. Every time the hover event is fired, the old tooltip instance is replaced with a new one which is why you see both. To fix this, put the declaration outside the event, like this:
ToolTip buttonToolTip = new ToolTip();
private void optionsvalueComboBox_MouseHover(object sender, EventArgs e)
{
buttonToolTip.ToolTipTitle = "Value";
buttonToolTip.UseFading = true;
buttonToolTip.UseAnimation = true;
buttonToolTip.IsBalloon = true;
buttonToolTip.ShowAlways = true;
buttonToolTip.AutoPopDelay = 5000;
buttonToolTip.InitialDelay = 1000;
buttonToolTip.ReshowDelay = 0;
buttonToolTip.SetToolTip(optionsvalueComboBox, optionsvalueComboBox.Text);
}
Now the same tooltip is being used with the wording simply being replaced. Let me know if this works for you!
I've tried digging in the MouseHover event of a ComboBox and looks like it doesn't work normally as we expect. The MouseHover is in fact fired only when you move the mouse over the drop down button if your ComboBox has style of dropdown. The simplest solution for this is change your combobox style to dropdownlist like this:
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
However that kind of style will make the ComboBox readonly. If that's not what you want, there is a work-around for you is to use the event MouseMove with a Timer to mimic the MouseHover, here is the code for you:
public partial class Form1 : Form {
public Form1(){
InitializeComponent();
t.Interval = 600;
t.Tick += (se, ev) => {
buttonToolTip.SetToolTip(comboBox1, (string)comboBox1.SelectedItem);
t.Stop();
};
//init the buttonToolTip
buttonToolTip.ToolTipTitle = "Value";
buttonToolTip.UseFading = true;
buttonToolTip.UseAnimation = true;
buttonToolTip.IsBalloon = true;
buttonToolTip.ShowAlways = true;
buttonToolTip.AutoPopDelay = 5000;
buttonToolTip.InitialDelay = 1000;
buttonToolTip.ReshowDelay = 0;
//register MouseMove event handler for your comboBox1
comboBox1.MouseMove += (se, ev) => {
//Restart the timer every time the mouse is moving
t.Stop();
t.Start();
};
}
Timer t = new Timer();
ToolTip buttonToolTip = new ToolTip();
}
A complete working example:
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public RECT(Rectangle rect)
{
Left = rect.Left;
Top = rect.Top;
Right = rect.Right;
Bottom = rect.Bottom;
}
public Rectangle Rect
{
get
{
return new Rectangle(Left, Top, Right - Left, Bottom - Top);
}
}
public Point Location
{
get
{
return new Point(Left, Top);
}
}
public int Left;
public int Top;
public int Right;
public int Bottom;
}
public class ToolTipComboBox: ComboBox
{
#region Fields
private ToolTip toolTip;
private bool _tooltipVisible;
private bool _dropDownOpen;
#endregion
#region Types
[StructLayout(LayoutKind.Sequential)]
// ReSharper disable once InconsistentNaming
public struct COMBOBOXINFO
{
public Int32 cbSize;
public RECT rcItem;
public RECT rcButton;
public ComboBoxButtonState buttonState;
public IntPtr hwndCombo;
public IntPtr hwndEdit;
public IntPtr hwndList;
}
public enum ComboBoxButtonState
{
// ReSharper disable once UnusedMember.Global
StateSystemNone = 0,
// ReSharper disable once UnusedMember.Global
StateSystemInvisible = 0x00008000,
// ReSharper disable once UnusedMember.Global
StateSystemPressed = 0x00000008
}
[DllImport("user32.dll")]
public static extern bool GetComboBoxInfo(IntPtr hWnd, ref COMBOBOXINFO pcbi);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
#endregion
#region Properties
private IntPtr HwndCombo
{
get
{
COMBOBOXINFO pcbi = new COMBOBOXINFO();
pcbi.cbSize = Marshal.SizeOf(pcbi);
GetComboBoxInfo(Handle, ref pcbi);
return pcbi.hwndCombo;
}
}
private IntPtr HwndDropDown
{
get
{
COMBOBOXINFO pcbi = new COMBOBOXINFO();
pcbi.cbSize = Marshal.SizeOf(pcbi);
GetComboBoxInfo(Handle, ref pcbi);
return pcbi.hwndList;
}
}
[Browsable(false)]
public new DrawMode DrawMode
{
get { return base.DrawMode; }
set { base.DrawMode = value; }
}
#endregion
#region ctor
public ToolTipComboBox()
{
toolTip = new ToolTip
{
UseAnimation = false,
UseFading = false
};
base.DrawMode = DrawMode.OwnerDrawFixed;
DrawItem += OnDrawItem;
DropDownClosed += OnDropDownClosed;
DropDown += OnDropDown;
MouseLeave += OnMouseLeave;
}
#endregion
#region Methods
private void OnDropDown(object sender, EventArgs e)
{
_dropDownOpen = true;
}
private void OnMouseLeave(object sender, EventArgs e)
{
ResetToolTip();
}
private void ShowToolTip(string text, int x, int y)
{
toolTip.Show(text, this, x, y);
_tooltipVisible = true;
}
private void OnDrawItem(object sender, DrawItemEventArgs e)
{
ComboBox cbo = sender as ComboBox;
if (e.Index == -1) return;
// ReSharper disable once PossibleNullReferenceException
string text = cbo.GetItemText(cbo.Items[e.Index]);
e.DrawBackground();
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
TextRenderer.DrawText(e.Graphics, text, e.Font, e.Bounds.Location, SystemColors.Window);
if (_dropDownOpen)
{
Size szText = TextRenderer.MeasureText(text, cbo.Font);
if (szText.Width > cbo.Width - SystemInformation.VerticalScrollBarWidth && !_tooltipVisible)
{
RECT rcDropDown;
GetWindowRect(HwndDropDown, out rcDropDown);
RECT rcCombo;
GetWindowRect(HwndCombo, out rcCombo);
if (rcCombo.Top > rcDropDown.Top)
{
ShowToolTip(text, e.Bounds.X, e.Bounds.Y - rcDropDown.Rect.Height - cbo.ItemHeight - 5);
}
else
{
ShowToolTip(text, e.Bounds.X, e.Bounds.Y + cbo.ItemHeight - cbo.ItemHeight);
}
}
}
}
else
{
ResetToolTip();
TextRenderer.DrawText(e.Graphics, text, e.Font, e.Bounds.Location, cbo.ForeColor);
}
e.DrawFocusRectangle();
}
private void OnDropDownClosed(object sender, EventArgs e)
{
_dropDownOpen = false;
ResetToolTip();
}
private void ResetToolTip()
{
if (_tooltipVisible)
{
// ReSharper disable once AssignNullToNotNullAttribute
toolTip.SetToolTip(this, null);
_tooltipVisible = false;
}
}
#endregion
}
Basically when user resizes my application's window I want application to be same size when application is re-opened again.
At first I though of handling SizeChanged event and save Height and Width, but I think there must be easier solution.
Pretty simple problem, but I can not find easy solution to it.
Save the values in the user.config file.
You'll need to create the value in the settings file - it should be in the Properties folder. Create five values:
Top of type double
Left of type double
Height of type double
Width of type double
Maximized of type bool - to hold whether the window is maximized or not. If you want to store more information then a different type or structure will be needed.
Initialise the first two to 0 and the second two to the default size of your application, and the last one to false.
Create a Window_OnSourceInitialized event handler and add the following:
this.Top = Properties.Settings.Default.Top;
this.Left = Properties.Settings.Default.Left;
this.Height = Properties.Settings.Default.Height;
this.Width = Properties.Settings.Default.Width;
// Very quick and dirty - but it does the job
if (Properties.Settings.Default.Maximized)
{
WindowState = WindowState.Maximized;
}
NOTE: The set window placement needs to go in the on source initialised event of the window not the constructor, otherwise if you have the window maximised on a second monitor, it will always restart maximised on the primary monitor and you won't be able to access it.
Create a Window_Closing event handler and add the following:
if (WindowState == WindowState.Maximized)
{
// Use the RestoreBounds as the current values will be 0, 0 and the size of the screen
Properties.Settings.Default.Top = RestoreBounds.Top;
Properties.Settings.Default.Left = RestoreBounds.Left;
Properties.Settings.Default.Height = RestoreBounds.Height;
Properties.Settings.Default.Width = RestoreBounds.Width;
Properties.Settings.Default.Maximized = true;
}
else
{
Properties.Settings.Default.Top = this.Top;
Properties.Settings.Default.Left = this.Left;
Properties.Settings.Default.Height = this.Height;
Properties.Settings.Default.Width = this.Width;
Properties.Settings.Default.Maximized = false;
}
Properties.Settings.Default.Save();
This will fail if the user makes the display area smaller - either by disconnecting a screen or changing the screen resolution - while the application is closed so you should add a check that the desired location and size is still valid before applying the values.
Actually you don't need to use code-behind to do that (except for saving the settings). You can use a custom markup extension to bind the window size and position to the settings like this :
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication1"
Title="Window1"
Height="{my:SettingBinding Height}"
Width="{my:SettingBinding Width}"
Left="{my:SettingBinding Left}"
Top="{my:SettingBinding Top}">
You can find the code for this markup extension here :
http://www.thomaslevesque.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/
While you can "roll your own" and manually save the settings somewhere, and in general it will work, it is very easy to not handle all of the cases correctly. It is much better to let the OS do the work for you, by calling GetWindowPlacement() at exit and SetWindowPlacement() at startup. It handles all of the crazy edge cases that can occur (multiple monitors, save the normal size of the window if it is closed while maximized, etc.) so that you don't have to.
This MSDN Sample shows how to use these with a WPF app. The sample isn't perfect (the window will start in the upper left corner as small as possible on first run, and there is some odd behavior with the Settings designer saving a value of type WINDOWPLACEMENT), but it should at least get you started.
The "long form" binding that Thomas posted above requires almost no coding, just make sure you have the namespace binding:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:p="clr-namespace:WpfApplication1.Properties"
Title="Window1"
Height="{Binding Source={x:Static p:Settings.Default}, Path=Height, Mode=TwoWay}"
Width="{Binding Source={x:Static p:Settings.Default}, Path=Width, Mode=TwoWay}"
Left="{Binding Source={x:Static p:Settings.Default}, Path=Left, Mode=TwoWay}"
Top="{Binding Source={x:Static p:Settings.Default}, Path=Top, Mode=TwoWay}">
Then to save on the code-behind:
private void frmMain_Closed(object sender, EventArgs e)
{
Properties.Settings.Default.Save();
}
Alternatively, you might like the following approach too (see source). Add the WindowSettings class to your project and insert WindowSettings.Save="True" in your main window's header:
<Window x:Class="YOURPROJECT.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Services="clr-namespace:YOURNAMESPACE.Services"
Services:WindowSettings.Save="True">
Where WindowSettings is defined as follows:
using System;
using System.ComponentModel;
using System.Configuration;
using System.Windows;
namespace YOURNAMESPACE.Services
{
/// <summary>
/// Persists a Window's Size, Location and WindowState to UserScopeSettings
/// </summary>
public class WindowSettings
{
#region Fields
/// <summary>
/// Register the "Save" attached property and the "OnSaveInvalidated" callback
/// </summary>
public static readonly DependencyProperty SaveProperty = DependencyProperty.RegisterAttached("Save", typeof (bool), typeof (WindowSettings), new FrameworkPropertyMetadata(OnSaveInvalidated));
private readonly Window mWindow;
private WindowApplicationSettings mWindowApplicationSettings;
#endregion Fields
#region Constructors
public WindowSettings(Window pWindow) { mWindow = pWindow; }
#endregion Constructors
#region Properties
[Browsable(false)] public WindowApplicationSettings Settings {
get {
if (mWindowApplicationSettings == null) mWindowApplicationSettings = CreateWindowApplicationSettingsInstance();
return mWindowApplicationSettings;
}
}
#endregion Properties
#region Methods
public static void SetSave(DependencyObject pDependencyObject, bool pEnabled) { pDependencyObject.SetValue(SaveProperty, pEnabled); }
protected virtual WindowApplicationSettings CreateWindowApplicationSettingsInstance() { return new WindowApplicationSettings(this); }
/// <summary>
/// Load the Window Size Location and State from the settings object
/// </summary>
protected virtual void LoadWindowState() {
Settings.Reload();
if (Settings.Location != Rect.Empty) {
mWindow.Left = Settings.Location.Left;
mWindow.Top = Settings.Location.Top;
mWindow.Width = Settings.Location.Width;
mWindow.Height = Settings.Location.Height;
}
if (Settings.WindowState != WindowState.Maximized) mWindow.WindowState = Settings.WindowState;
}
/// <summary>
/// Save the Window Size, Location and State to the settings object
/// </summary>
protected virtual void SaveWindowState() {
Settings.WindowState = mWindow.WindowState;
Settings.Location = mWindow.RestoreBounds;
Settings.Save();
}
/// <summary>
/// Called when Save is changed on an object.
/// </summary>
private static void OnSaveInvalidated(DependencyObject pDependencyObject, DependencyPropertyChangedEventArgs pDependencyPropertyChangedEventArgs) {
var window = pDependencyObject as Window;
if (window != null)
if ((bool) pDependencyPropertyChangedEventArgs.NewValue) {
var settings = new WindowSettings(window);
settings.Attach();
}
}
private void Attach() {
if (mWindow != null) {
mWindow.Closing += WindowClosing;
mWindow.Initialized += WindowInitialized;
mWindow.Loaded += WindowLoaded;
}
}
private void WindowClosing(object pSender, CancelEventArgs pCancelEventArgs) { SaveWindowState(); }
private void WindowInitialized(object pSender, EventArgs pEventArgs) { LoadWindowState(); }
private void WindowLoaded(object pSender, RoutedEventArgs pRoutedEventArgs) { if (Settings.WindowState == WindowState.Maximized) mWindow.WindowState = Settings.WindowState; }
#endregion Methods
#region Nested Types
public class WindowApplicationSettings : ApplicationSettingsBase
{
#region Constructors
public WindowApplicationSettings(WindowSettings pWindowSettings) { }
#endregion Constructors
#region Properties
[UserScopedSetting] public Rect Location {
get {
if (this["Location"] != null) return ((Rect) this["Location"]);
return Rect.Empty;
}
set { this["Location"] = value; }
}
[UserScopedSetting] public WindowState WindowState {
get {
if (this["WindowState"] != null) return (WindowState) this["WindowState"];
return WindowState.Normal;
}
set { this["WindowState"] = value; }
}
#endregion Properties
}
#endregion Nested Types
}
}
There's a NuGet Project RestoreWindowPlace
see on github that does all this for you, saving the information in an XML file.
To get it to work on a window, it's as simple as calling:
((App)Application.Current).WindowPlace.Register(this);
In App you create the class that manages your windows. See the github link above for more information.
I made a more generic solution based on RandomEngys brilliant answer. It saves the position to file in the running folder and you don't need to create new properties for each new window you create. This sollution works great for me with minimal code in code behind.
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Interop;
using System.Xml;
using System.Xml.Serialization;
namespace WindowPlacementNameSpace
{
// RECT structure required by WINDOWPLACEMENT structure
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public RECT(int left, int top, int right, int bottom)
{
this.Left = left;
this.Top = top;
this.Right = right;
this.Bottom = bottom;
}
}
// POINT structure required by WINDOWPLACEMENT structure
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
// WINDOWPLACEMENT stores the position, size, and state of a window
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPLACEMENT
{
public int length;
public int flags;
public int showCmd;
public POINT minPosition;
public POINT maxPosition;
public RECT normalPosition;
}
public static class WindowPlacement
{
private static readonly Encoding Encoding = new UTF8Encoding();
private static readonly XmlSerializer Serializer = new XmlSerializer(typeof(WINDOWPLACEMENT));
[DllImport("user32.dll")]
private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll")]
private static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private static void SetPlacement(IntPtr windowHandle, string placementXml)
{
if (string.IsNullOrEmpty(placementXml))
{
return;
}
byte[] xmlBytes = Encoding.GetBytes(placementXml);
try
{
WINDOWPLACEMENT placement;
using (MemoryStream memoryStream = new MemoryStream(xmlBytes))
{
placement = (WINDOWPLACEMENT)Serializer.Deserialize(memoryStream);
}
placement.length = Marshal.SizeOf(typeof(WINDOWPLACEMENT));
placement.flags = 0;
placement.showCmd = (placement.showCmd == SW_SHOWMINIMIZED ? SW_SHOWNORMAL : placement.showCmd);
SetWindowPlacement(windowHandle, ref placement);
}
catch (InvalidOperationException)
{
// Parsing placement XML failed. Fail silently.
}
}
private static string GetPlacement(IntPtr windowHandle)
{
WINDOWPLACEMENT placement;
GetWindowPlacement(windowHandle, out placement);
using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
{
Serializer.Serialize(xmlTextWriter, placement);
byte[] xmlBytes = memoryStream.ToArray();
return Encoding.GetString(xmlBytes);
}
}
}
public static void ApplyPlacement(this Window window)
{
var className = window.GetType().Name;
try
{
var pos = File.ReadAllText(Directory + "\\" + className + ".pos");
SetPlacement(new WindowInteropHelper(window).Handle, pos);
}
catch (Exception exception)
{
Log.Error("Couldn't read position for " + className, exception);
}
}
public static void SavePlacement(this Window window)
{
var className = window.GetType().Name;
var pos = GetPlacement(new WindowInteropHelper(window).Handle);
try
{
File.WriteAllText(Directory + "\\" + className + ".pos", pos);
}
catch (Exception exception)
{
Log.Error("Couldn't write position for " + className, exception);
}
}
private static string Directory => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
}
In your code behind you add these two methods
///This method is save the actual position of the window to file "WindowName.pos"
private void ClosingTrigger(object sender, EventArgs e)
{
this.SavePlacement();
}
///This method is load the actual position of the window from the file
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
this.ApplyPlacement();
}
in the xaml window you add this
Closing="ClosingTrigger"
The default way of solving it is to use settings files. The problem with settings files is that you have to define all the settings and write the code that copies data back and forth yourself. Quite tedious if you have a lot of properties to keep track of.
I made a pretty flexible and very easy to use library for this, you just tell it which properties of which object to track and it does the rest. You can configure the crap out of it too if you like.
The library is called Jot (github), here is an old CodeProject article I wrote about it.
Here's how you'd use it to keep track of a window's size and location:
public MainWindow()
{
InitializeComponent();
_stateTracker.Configure(this)
.IdentifyAs("MyMainWindow")
.AddProperties(nameof(Height), nameof(Width), nameof(Left), nameof(Top), nameof(WindowState))
.RegisterPersistTrigger(nameof(Closed))
.Apply();
}
Jot vs. settings files: With Jot there's considerably less code, and it's a lot less error prone since you only need to mention each property once.
With settings files you need to mention each property 5 times: once when you explicitly create the property and an additional four times in the code that copies the values back and forth.
Storage, serialization etc are completely configurable. Also, when using IOC, you can even hook it up so that it applies tracking automatically to all objects it resolves so that all you need to do to make a property persistent is slap a [Trackable] attribute on it.
I'm writing all this because I think the library is top notch and I want to mouth off about it.
I wrote a quick class which does this. Here is how it's called:
public MainWindow()
{
FormSizeSaver.RegisterForm(this, () => Settings.Default.MainWindowSettings,
s =>
{
Settings.Default.MainWindowSettings = s;
Settings.Default.Save();
});
InitializeComponent();
...
And here is the code:
public class FormSizeSaver
{
private readonly Window window;
private readonly Func<FormSizeSaverSettings> getSetting;
private readonly Action<FormSizeSaverSettings> saveSetting;
private FormSizeSaver(Window window, Func<string> getSetting, Action<string> saveSetting)
{
this.window = window;
this.getSetting = () => FormSizeSaverSettings.FromString(getSetting());
this.saveSetting = s => saveSetting(s.ToString());
window.Initialized += InitializedHandler;
window.StateChanged += StateChangedHandler;
window.SizeChanged += SizeChangedHandler;
window.LocationChanged += LocationChangedHandler;
}
public static FormSizeSaver RegisterForm(Window window, Func<string> getSetting, Action<string> saveSetting)
{
return new FormSizeSaver(window, getSetting, saveSetting);
}
private void SizeChangedHandler(object sender, SizeChangedEventArgs e)
{
var s = getSetting();
s.Height = e.NewSize.Height;
s.Width = e.NewSize.Width;
saveSetting(s);
}
private void StateChangedHandler(object sender, EventArgs e)
{
var s = getSetting();
if (window.WindowState == WindowState.Maximized)
{
if (!s.Maximized)
{
s.Maximized = true;
saveSetting(s);
}
}
else if (window.WindowState == WindowState.Normal)
{
if (s.Maximized)
{
s.Maximized = false;
saveSetting(s);
}
}
}
private void InitializedHandler(object sender, EventArgs e)
{
var s = getSetting();
window.WindowState = s.Maximized ? WindowState.Maximized : WindowState.Normal;
if (s.Height != 0 && s.Width != 0)
{
window.Height = s.Height;
window.Width = s.Width;
window.WindowStartupLocation = WindowStartupLocation.Manual;
window.Left = s.XLoc;
window.Top = s.YLoc;
}
}
private void LocationChangedHandler(object sender, EventArgs e)
{
var s = getSetting();
s.XLoc = window.Left;
s.YLoc = window.Top;
saveSetting(s);
}
}
[Serializable]
internal class FormSizeSaverSettings
{
public double Height, Width, YLoc, XLoc;
public bool Maximized;
public override string ToString()
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
byte[] buffer = new byte[(int)ms.Length];
ms.Read(buffer, 0, buffer.Length);
return Convert.ToBase64String(buffer);
}
}
internal static FormSizeSaverSettings FromString(string value)
{
try
{
using (var ms = new MemoryStream(Convert.FromBase64String(value)))
{
var bf = new BinaryFormatter();
return (FormSizeSaverSettings) bf.Deserialize(ms);
}
}
catch (Exception)
{
return new FormSizeSaverSettings();
}
}
}
Create a string named WindowXml in your default Settings.
Use this extension method on your Window Loaded and Closing events to restore and save Window size and location.
using YourProject.Properties;
using System;
using System.Linq;
using System.Windows;
using System.Xml.Linq;
namespace YourProject.Extensions
{
public static class WindowExtensions
{
public static void SaveSizeAndLocation(this Window w)
{
try
{
var s = "<W>";
s += GetNode("Top", w.WindowState == WindowState.Maximized ? w.RestoreBounds.Top : w.Top);
s += GetNode("Left", w.WindowState == WindowState.Maximized ? w.RestoreBounds.Left : w.Left);
s += GetNode("Height", w.WindowState == WindowState.Maximized ? w.RestoreBounds.Height : w.Height);
s += GetNode("Width", w.WindowState == WindowState.Maximized ? w.RestoreBounds.Width : w.Width);
s += GetNode("WindowState", w.WindowState);
s += "</W>";
Settings.Default.WindowXml = s;
Settings.Default.Save();
}
catch (Exception)
{
}
}
public static void RestoreSizeAndLocation(this Window w)
{
try
{
var xd = XDocument.Parse(Settings.Default.WindowXml);
w.WindowState = (WindowState)Enum.Parse(typeof(WindowState), xd.Descendants("WindowState").FirstOrDefault().Value);
w.Top = Convert.ToDouble(xd.Descendants("Top").FirstOrDefault().Value);
w.Left = Convert.ToDouble(xd.Descendants("Left").FirstOrDefault().Value);
w.Height = Convert.ToDouble(xd.Descendants("Height").FirstOrDefault().Value);
w.Width = Convert.ToDouble(xd.Descendants("Width").FirstOrDefault().Value);
}
catch (Exception)
{
}
}
private static string GetNode(string name, object value)
{
return string.Format("<{0}>{1}</{0}>", name, value);
}
}
}
You might like this:
public class WindowStateHelper
{
public static string ToXml(System.Windows.Window win)
{
XElement bounds = new XElement("Bounds");
if (win.WindowState == System.Windows.WindowState.Maximized)
{
bounds.Add(new XElement("Top", win.RestoreBounds.Top));
bounds.Add(new XElement("Left", win.RestoreBounds.Left));
bounds.Add(new XElement("Height", win.RestoreBounds.Height));
bounds.Add(new XElement("Width", win.RestoreBounds.Width));
}
else
{
bounds.Add(new XElement("Top", win.Top));
bounds.Add(new XElement("Left", win.Left));
bounds.Add(new XElement("Height", win.Height));
bounds.Add(new XElement("Width", win.Width));
}
XElement root = new XElement("WindowState",
new XElement("State", win.WindowState.ToString()),
new XElement("Visibility", win.Visibility.ToString()),
bounds);
return root.ToString();
}
public static void FromXml(string xml, System.Windows.Window win)
{
try
{
XElement root = XElement.Parse(xml);
string state = root.Descendants("State").FirstOrDefault().Value;
win.WindowState = (System.Windows.WindowState)Enum.Parse(typeof(System.Windows.WindowState), state);
state = root.Descendants("Visibility").FirstOrDefault().Value;
win.Visibility = (System.Windows.Visibility)Enum.Parse(typeof(System.Windows.Visibility), state);
XElement bounds = root.Descendants("Bounds").FirstOrDefault();
win.Top = Convert.ToDouble(bounds.Element("Top").Value);
win.Left = Convert.ToDouble(bounds.Element("Left").Value);
win.Height = Convert.ToDouble(bounds.Element("Height").Value);
win.Width = Convert.ToDouble(bounds.Element("Width").Value);
}
catch (Exception x)
{
System.Console.WriteLine(x.ToString());
}
}
}
When the app closes:
Properties.Settings.Default.Win1Placement = WindowStateHelper.ToXml(win1);
Properties.Settings.Default.Win2Placement = WindowStateHelper.ToXml(win2);
...
When the app starts:
WindowStateHelper.FromXml(Properties.Settings.Default.Win1Placement, win1);
WindowStateHelper.FromXml(Properties.Settings.Default.Win2Placement, win2);
...
I'm using the answer from Lance Cleveland and bind the Setting.
But i'm using some more Code to avoid that my Window is out of Screen.
private void SetWindowSettingsIntoScreenArea()
{
// first detect Screen, where we will display the Window
// second correct bottom and right position
// then the top and left position.
// If Size is bigger than current Screen, it's still possible to move and size the Window
// get the screen to display the window
var screen = System.Windows.Forms.Screen.FromPoint(new System.Drawing.Point((int)Default.Left, (int)Default.Top));
// is bottom position out of screen for more than 1/3 Height of Window?
if (Default.Top + (Default.Height / 3) > screen.WorkingArea.Height)
Default.Top = screen.WorkingArea.Height - Default.Height;
// is right position out of screen for more than 1/2 Width of Window?
if (Default.Left + (Default.Width / 2) > screen.WorkingArea.Width)
Default.Left = screen.WorkingArea.Width - Default.Width;
// is top position out of screen?
if (Default.Top < screen.WorkingArea.Top)
Default.Top = screen.WorkingArea.Top;
// is left position out of screen?
if (Default.Left < screen.WorkingArea.Left)
Default.Left = screen.WorkingArea.Left;
}