How to grayscale an entire WPF application - wpf

A user requested a grayscale version of my WPF application. The application supports different color themes and has text and images. Obviously, one way to this is to create a grayscale theme. But in my mind, it might be better to add a toggle that grayscales the current theme on demand. This got me to wondering if there is a way to grayscale an entire WPF application. I looked at pixel shaders briefly but it doesn't appear I can apply one globally to an app. Looking for suggestions on how to do this.

While a dedicated theme would be the best choice, it's a tremendous amount of work.
Since it's a single user ask - you may want to try a pixel shader and gather some feedback from the user and see if it works. If not, you can look into doing a dedicated theme.
Here is a pixel shader that works really well with different colors, contrasts, and brightness of colors. It uses the HSP color model, which you can learn about here:
http://alienryderflex.com/hsp.html
sampler2D implicitInput : register(s0);
float factor : register(c0);
/// <summary>The brightness offset.</summary>
/// <minValue>-1</minValue>
/// <maxValue>1</maxValue>
/// <defaultValue>0</defaultValue>
float brightness : register(c1);
float4 main(float2 uv : TEXCOORD) : COLOR
{
float4 pixelColor = tex2D(implicitInput, uv);
pixelColor.rgb /= pixelColor.a;
// Apply brightness.
pixelColor.rgb += brightness;
// Return final pixel color.
pixelColor.rgb *= pixelColor.a;
float4 color = pixelColor;
float pr = .299;
float pg = .587;
float pb = .114;
float gray = sqrt(color.r * color.r * pr + color.g * color.g * pg + color.b * color.b * pb);
float4 result;
result.r = (color.r - gray) * factor + gray;
result.g = (color.g - gray) * factor + gray;
result.b = (color.b - gray) * factor + gray;
result.a = color.a;
return result;
}
You will need to compile the shader to a .ps file.
Here is the wrapper class:
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
namespace Shaders
{
/// <summary>
/// Represents a grayscale pixel shader effect using the HSP method.
/// </summary>
public class GrayscaleHspEffect : ShaderEffect
{
/// <summary>
/// Identifies the Input property.
/// </summary>
public static readonly DependencyProperty InputProperty = RegisterPixelShaderSamplerProperty("Input", typeof(GrayscaleHspEffect), 0);
/// <summary>
/// Identifies the Factor property.
/// </summary>
public static readonly DependencyProperty FactorProperty = DependencyProperty.Register("Factor", typeof(double), typeof(GrayscaleHspEffect), new UIPropertyMetadata(0D, PixelShaderConstantCallback(0)));
/// <summary>
/// Identifies the Brightness property.
/// </summary>
public static readonly DependencyProperty BrightnessProperty = DependencyProperty.Register("Brightness", typeof(double), typeof(GrayscaleHspEffect), new UIPropertyMetadata(0D, PixelShaderConstantCallback(1)));
/// <summary>
/// Creates a new instance of the <see cref="GrayscaleHspEffect"/> class.
/// </summary>
public GrayscaleHspEffect()
{
var pixelShader = new PixelShader();
pixelShader.UriSource = new Uri("/Shaders;component/Effects/GrayscaleHspEffect.ps", UriKind.Relative);
PixelShader = pixelShader;
UpdateShaderValue(InputProperty);
UpdateShaderValue(FactorProperty);
UpdateShaderValue(BrightnessProperty);
}
/// <summary>
/// Gets or sets the <see cref="Brush"/> used as input for the shader.
/// </summary>
public Brush Input
{
get => ((Brush)(GetValue(InputProperty)));
set => SetValue(InputProperty, value);
}
/// <summary>
/// Gets or sets the factor used in the shader.
/// </summary>
public double Factor
{
get => ((double)(GetValue(FactorProperty)));
set => SetValue(FactorProperty, value);
}
/// <summary>
/// Gets or sets the brightness of the effect.
/// </summary>
public double Brightness
{
get => ((double)(GetValue(BrightnessProperty)));
set => SetValue(BrightnessProperty, value);
}
}
}

Related

Child control handling touch event affects multi-point manipulation

I have a UserControl that must respond to TouchUp events and this sits within a Viewbox which needs to be panned and scaled with pinch manipulation. Touch events on the control are handled fine. However pinch manipulations only scale the ViewPort if both pinch points are contained entirely within either the user control or the Viewport space around it. If the pinch straddles the user control boundary then the ManipulationDelta loses one of the points and reports a scale of (1,1).
If I remove IsManipulationEnabled="True" from the control handling the TouchUp event then the scaling works but the touch event doesn’t fire.
What can I do to retain the manipulation across the ViewPort whilst also handling the touch event in the user control?
Test Solution
<Window x:Class="TouchTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Touch Test"
Height="400"
Width="700"
ManipulationDelta="OnManipulationDelta"
ManipulationStarting="OnManipulationStarting">
<Grid Background="Transparent"
IsManipulationEnabled="True">
<Viewbox x:Name="Viewbox"
Stretch="Uniform">
<Viewbox.RenderTransform>
<MatrixTransform/>
</Viewbox.RenderTransform>
<Grid Width="800"
Height="800"
Background="LightGreen"
IsManipulationEnabled="True"
TouchUp="OnTouchUp">
<TextBlock x:Name="TimeTextBlock"
FontSize="100"
TextAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</Viewbox>
<TextBlock x:Name="ScaleTextBlock"
FontSize="10"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"/>
</Grid>
</Window>
Handlers in code-behind:
private void OnTouchUp(object sender, TouchEventArgs e)
{
TimeTextBlock.Text = DateTime.Now.ToString("H:mm:ss.fff");
}
private void OnManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
e.ManipulationContainer = this;
}
private void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
if (Viewbox == null)
{
return;
}
ManipulationDelta delta = e.DeltaManipulation;
ScaleTextBlock.Text = $"Delta Scale: {delta.Scale}";
MatrixTransform transform = Viewbox.RenderTransform as MatrixTransform;
if (transform == null)
{
return;
}
Matrix matrix = transform.Matrix;
Point position = ((FrameworkElement)e.ManipulationContainer).TranslatePoint(e.ManipulationOrigin, Viewbox);
position = matrix.Transform(position);
matrix = MatrixTransformations.ScaleAtPoint(matrix, delta.Scale.X, delta.Scale.Y, position);
matrix = MatrixTransformations.PreventNegativeScaling(matrix);
matrix = MatrixTransformations.Translate(matrix, delta.Translation);
matrix = MatrixTransformations.ConstrainOffset(Viewbox.RenderSize, matrix);
transform.Matrix = matrix;
}
Supporting class:
public static class MatrixTransformations
{
/// <summary>
/// Prevent the transformation from being offset beyond the given size rectangle.
/// </summary>
/// <param name="size"></param>
/// <param name="matrix"></param>
/// <returns></returns>
public static Matrix ConstrainOffset(Size size, Matrix matrix)
{
double distanceBetweenViewRightEdgeAndActualWindowRight = size.Width * matrix.M11 - size.Width + matrix.OffsetX;
double distanceBetweenViewBottomEdgeAndActualWindowBottom = size.Height * matrix.M22 - size.Height + matrix.OffsetY;
if (distanceBetweenViewRightEdgeAndActualWindowRight < 0)
{
// Moved in the x-axis too far left. Snap back to limit
matrix.OffsetX -= distanceBetweenViewRightEdgeAndActualWindowRight;
}
if (distanceBetweenViewBottomEdgeAndActualWindowBottom < 0)
{
// Moved in the x-axis too far left. Snap back to limit
matrix.OffsetY -= distanceBetweenViewBottomEdgeAndActualWindowBottom;
}
// Prevent positive offset
matrix.OffsetX = Math.Min(0.0, matrix.OffsetX);
matrix.OffsetY = Math.Min(0.0, matrix.OffsetY);
return matrix;
}
/// <summary>
/// Prevent the transformation from performing a negative scale.
/// </summary>
/// <param name="matrix"></param>
/// <returns></returns>
public static Matrix PreventNegativeScaling(Matrix matrix)
{
matrix.M11 = Math.Max(1.0, matrix.M11);
matrix.M22 = Math.Max(1.0, matrix.M22);
return matrix;
}
/// <summary>
/// Translate the matrix by the given vector to providing panning.
/// </summary>
/// <param name="matrix"></param>
/// <param name="vector"></param>
/// <returns></returns>
public static Matrix Translate(Matrix matrix, Vector vector)
{
matrix.Translate(vector.X, vector.Y);
return matrix;
}
/// <summary>
/// Scale the matrix by the given X/Y factors centered at the given point.
/// </summary>
/// <param name="matrix"></param>
/// <param name="scaleX"></param>
/// <param name="scaleY"></param>
/// <param name="point"></param>
/// <returns></returns>
public static Matrix ScaleAtPoint(Matrix matrix, double scaleX, double scaleY, Point point)
{
matrix.ScaleAt(scaleX, scaleY, point.X, point.Y);
return matrix;
}
}
So, I'm not a wpf programmer. But have a suggestion/workaround which could possibly work for you.
You could code the thing as follows:
set IsManipulationEnabled="True" (in this case OnTouchUp isn't fired for the grid colored in LightGreen)
Set OnTouchUp to fire on either Viewbox x:Name="Viewbox" or the Grid above this Viewbox (rather than for the 800x800 Grid)
So now OnTouchUp would be fired whenever you touch anywhere in the Viewbox (not just inside the LightGreen area)
When OnTouchUp is now fired, just check if the co-ordinates are in the region of LightGreen box. If YES-> update the time, if no, leave the time as it is.
I understand this is a workaround. Still posted an answer, in case it could prove useful.
i am not sure the sample you post reflect totally your code...but what i see : you do not manage the ManipulationCompleted and LostMouseCapture. Also you do not make any MouseCapture() MouseRelease() so when the manipulation outbound the window you loose it....search "mouse capture" on this repo, you will see even if no manipulation event that this is quite complicated....https://github.com/TheCamel/ArchX/search?utf8=%E2%9C%93&q=mouse+capture&type=

XNA Arrays and drawing textures?

I am completely new to coding and have only been practicing for a few weeks and i have been assigned a task in which seems simple has hit a stumbling block
i have 4 sprites on screen drawn but i have to every time the game starts the sprites have to be random chosen between 1 sprite or the other as well out of the 2 sprites there must be at least one of each sprite on screen.
my tutor suggested that i use an array to store the textures and then code it so it randomly picks which one to draw each time
namespace GamesProgrammingAssement1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
KeyboardState keys;
KeyboardState oldKeys;
GamePadState Pad1;
GamePadState oldPad1;
Texture2D gnome;
Texture2D troll;
Rectangle sprRect1;
Rectangle sprRect2;
Rectangle sprRect3;
Rectangle sprRect4;
SpriteFont Run;
SpriteFont Score;
int scoreNum = 0;
int runNum = 0;
Vector2 scorePos;
Vector2 runPos;
Texture2D[] sprite = new Texture2D[2];
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
sprRect1 = new Rectangle(375, 100, 64, 64);
sprRect2 = new Rectangle(375, 300, 64, 64);
sprRect3 = new Rectangle(225, 200, 64, 64);
sprRect4 = new Rectangle(525, 200, 64, 64);
scorePos = new Vector2(5, 400);
runPos = new Vector2(5, 425);
sprite[0] = gnome;
sprite[1] = troll;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
gnome = Content.Load<Texture2D>("Gnome");
troll = Content.Load<Texture2D>("Troll");
Score = Content.Load<SpriteFont>("Score");
Run = Content.Load<SpriteFont>("Run");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
KeyboardState keys = Keyboard.GetState();
KeyboardState oldkeys = keys;
if (keys.IsKeyDown(Keys.Escape)) this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(gnome,sprRect1,Color.White);
spriteBatch.Draw(troll, sprRect2,Color.White);
spriteBatch.Draw(troll, sprRect3, Color.White);
spriteBatch.Draw(troll, sprRect4, Color.White);
spriteBatch.DrawString(Score, "SCORE : "+ scoreNum, scorePos, Color.Black);
spriteBatch.DrawString(Run, "RUN OF TROLL : " + runNum, runPos, Color.Black);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
any help would be great because i dont know if im storing the arrays properly or if im doing random right
I see you are storing your Textures in an Array. I do not see any code for Random in your sample.
That being said, consider the following function:
Random rand = new Random();
private Texture2D GetRandomTexture()
{
return sprite[rand.Next(0, 2)];
}
Calling this function, will return a random texture contained in your "sprite" array. Plugging this function call in your draw could resemble something like this:
spriteBatch.Draw(GetRandomTexture(), sprRect1, Color.White);
Since you declared that you are a beginner, I tried not to go too much into details. You should, however, considering looking into creating a new class "Sprite" that would contain the Texture2D, Position, Rectangle values of each of your sprites. Then instead of storing an array of Textures, you would be able of storing an array (or list) of Sprite objects.
You want to choose four sprites, therefore you should use an array (or similar structure) which can contain four elements:
Texture2D[] sprites = new Texture2D[4];
When initializing the Array there are three possible situations regarding how many of each sprite will exist:
1-3 (one troll, three gnomes)
2-2 (two of each)
3-1 (three trolls, one gnome)
So firstly, you have to pick one of these distributions:
var rnd = new Random();
var trolls = rnd.Next(1, 3);
var gnomes = 4 - trolls;
Then, you can fill the array:
for(int i = 0; i < 4; ++i)
{
if(gnomes == 0)
{
//choose the troll
sprites[i] = troll;
--trolls;
}
else if(trolls == 0)
{
//choose the gnome
sprites[i] = gnome;
--gnomes;
}
else
{
//choose randomly
if(rnd.Next(2) < 1)
{
sprites[i] = troll;
--trolls;
}
else
{
sprites[i] = gnome;
--gnomes;
}
}
}
You draw them like
spriteBatch.Draw(sprites[0], sprRect1,Color.White);
spriteBatch.Draw(sprites[1], , sprRect2,Color.White);
spriteBatch.Draw(sprites[2], , sprRect3, Color.White);
spriteBatch.Draw(sprites[3], , sprRect4, Color.White);

Silverlight Image Panning

I am working on silverlight application and I had use the pixel shadder with brightness and contrast which is working fine. so I had tried with panning center x,y but it will not working so how I can add this panning.
My PS file like this.
/// <class>briconEffect</class>
/// <description>An effect that controls brightness and contrast.</description>
//-----------------------------------------------------------------------------------------
// Shader constant register mappings (scalars - float, double, Point, Color, Point3D, etc.)
//-----------------------------------------------------------------------------------------
/// <summary>The brightness offset.</summary>
/// <minValue>-1</minValue>
/// <maxValue>1</maxValue>
/// <defaultValue>0</defaultValue>
float Brightness : register(C0);
/// <summary>The contrast multiplier.</summary>
/// <minValue>0</minValue>
/// <maxValue>2</maxValue>
/// <defaultValue>1.5</defaultValue>
float Contrast : register(C1);
/// <summary>The gamma correction exponent.</summary>
/// <minValue>0.5</minValue>
/// <maxValue>2</maxValue>
/// <defaultValue>0.8</defaultValue>
float Gamma : register(C2);
/// <summary>Change the ratio between the Red channel</summary>
/// <minValue>0/minValue>
/// <maxValue>1</maxValue>
/// <defaultValue>0.5</defaultValue>
float RedRatio : register(C3);
/// <summary>Change the ratio between the Blue channel </summary>
/// <minValue>0/minValue>
/// <maxValue>1</maxValue>
/// <defaultValue>0.5</defaultValue>
float BlueRatio : register(C4);
/// <summary>Change the ratio between the Green channel</summary>
/// <minValue>0/minValue>
/// <maxValue>1</maxValue>
/// <defaultValue>0.5</defaultValue>
float GreenRatio : register(C5);
//--------------------------------------------------------------------------------------
// Sampler Inputs (Brushes, including Texture1)
//--------------------------------------------------------------------------------------
sampler2D Texture1Sampler : register(S0);
//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 main(float2 uv : TEXCOORD) : COLOR
{
float4 pixelColor = tex2D(Texture1Sampler, uv);
pixelColor.rgb = pow(pixelColor.rgb, Gamma);
pixelColor.rgb /= pixelColor.a;
// Apply contrast.
pixelColor.rgb = ((pixelColor.rgb - 0.5f) * max(Contrast, 0)) + 0.5f;
// Apply brightness.
pixelColor.rgb += Brightness;
// Return final pixel color.
pixelColor.rgb *= pixelColor.a;
pixelColor.r = pixelColor.r * (1-RedRatio ) ;
pixelColor.b = pixelColor.b * (1-BlueRatio ) ;
pixelColor.g = pixelColor.g * (1-GreenRatio ) ;
return pixelColor;
}

Validation in textbox in WPF

I am currently working on a WPF application where I would like to have a TextBox that can only have numeric entries in it. I know that I can validate the content of it when I lost the focus and block the content from being numeric, but in other Windows Form application, we use to totally block any input except numerical from being written down. Plus, we use to put that code in a separate dll to reference it in many places.
Here is the code in 2008 not using WPF:
Public Shared Sub BloquerInt(ByRef e As System.Windows.Forms.KeyPressEventArgs, ByRef oTxt As Windows.Forms.TextBox, ByVal intlongueur As Integer)
Dim intLongueurSelect As Integer = oTxt.SelectionLength
Dim intPosCurseur As Integer = oTxt.SelectionStart
Dim strValeurTxtBox As String = oTxt.Text.Substring(0, intPosCurseur) & oTxt.Text.Substring(intPosCurseur + intLongueurSelect, oTxt.Text.Length - intPosCurseur - intLongueurSelect)
If IsNumeric(e.KeyChar) OrElse _
Microsoft.VisualBasic.Asc(e.KeyChar) = System.Windows.Forms.Keys.Back Then
If Microsoft.VisualBasic.AscW(e.KeyChar) = System.Windows.Forms.Keys.Back Then
e.Handled = False
ElseIf strValeurTxtBox.Length < intlongueur Then
e.Handled = False
Else
e.Handled = True
End If
Else
e.Handled = True
End If
Is there an equivalent way in WPF? I wouldn't mind if this is in a style but I am new to WPF so style are a bit obscure to what they can or can't do.
You can restrict the input to numbers only using an attached property on the TextBox. Define the attached property once (even in a separate dll) and use it on any TextBox. Here is the attached property:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
/// <summary>
/// Class that provides the TextBox attached property
/// </summary>
public static class TextBoxService
{
/// <summary>
/// TextBox Attached Dependency Property
/// </summary>
public static readonly DependencyProperty IsNumericOnlyProperty = DependencyProperty.RegisterAttached(
"IsNumericOnly",
typeof(bool),
typeof(TextBoxService),
new UIPropertyMetadata(false, OnIsNumericOnlyChanged));
/// <summary>
/// Gets the IsNumericOnly property. This dependency property indicates the text box only allows numeric or not.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to get the property from</param>
/// <returns>The value of the StatusBarContent property</returns>
public static bool GetIsNumericOnly(DependencyObject d)
{
return (bool)d.GetValue(IsNumericOnlyProperty);
}
/// <summary>
/// Sets the IsNumericOnly property. This dependency property indicates the text box only allows numeric or not.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to set the property on</param>
/// <param name="value">value of the property</param>
public static void SetIsNumericOnly(DependencyObject d, bool value)
{
d.SetValue(IsNumericOnlyProperty, value);
}
/// <summary>
/// Handles changes to the IsNumericOnly property.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> that fired the event</param>
/// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param>
private static void OnIsNumericOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
bool isNumericOnly = (bool)e.NewValue;
TextBox textBox = (TextBox)d;
if (isNumericOnly)
{
textBox.PreviewTextInput += BlockNonDigitCharacters;
textBox.PreviewKeyDown += ReviewKeyDown;
}
else
{
textBox.PreviewTextInput -= BlockNonDigitCharacters;
textBox.PreviewKeyDown -= ReviewKeyDown;
}
}
/// <summary>
/// Disallows non-digit character.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An <see cref="TextCompositionEventArgs"/> that contains the event data.</param>
private static void BlockNonDigitCharacters(object sender, TextCompositionEventArgs e)
{
foreach (char ch in e.Text)
{
if (!Char.IsDigit(ch))
{
e.Handled = true;
}
}
}
/// <summary>
/// Disallows a space key.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An <see cref="KeyEventArgs"/> that contains the event data.</param>
private static void ReviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
// Disallow the space key, which doesn't raise a PreviewTextInput event.
e.Handled = true;
}
}
}
Here is how to use it (replace "controls" with your own namespace):
<TextBox controls:TextBoxService.IsNumericOnly="True" />
You can put a validation in your binding
<TextBox>
<TextBox.Text>
<Binding Path="CategoriaSeleccionada.ColorFondo"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<utilities:RGBValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Look at this example (of my program), you put the validation inside the binding like this. With UpdateSourceTrigger you can change when you binding will be updated (lost focus, in every change...)
Well, the validation is a class, I will put you an example:
class RGBValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
// Here you make your validation using the value object.
// If you want to check if the object is only numbers you can
// Use some built-in method
string blah = value.ToString();
int num;
bool isNum = int.TryParse(blah, out num);
if (isNum) return new ValidationResult(true, null);
else return new ValidationResult(false, "It's no a number");
}
}
In short, do the job inside that method and return a new ValidationResult. The first parameter is a bool, true if the validation is good, false if not. The second parameter is only a message for information.
I think that this is the basics of textbox validation.
Hope this help.
EDIT: Sorry, I don't know VB.NET but I think that the C# code is pretty simple.

Formatting text in WinForm Label

Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out.
For example:
Dim myLabel As New Label
myLabel.Text = "This is <b>bold</b> text. This is <i>italicized</i> text."
Which would produce the text in the label as:
This is bold text. This is
italicized text.
That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options:
Use separate labels
Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text
Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2.
Not really, but you could fake it with a read-only RichTextBox without borders. RichTextBox supports Rich Text Format (rtf).
Another workaround, late to the party: if you don't want to use a third party control, and you're just looking to call attention to some of the text in your label, and you're ok with underlines, you can use a LinkLabel.
Note that many consider this a 'usability crime', but if you're not designing something for end user consumption then it may be something you're prepared to have on your conscience.
The trick is to add disabled links to the parts of your text that you want underlined, and then globally set the link colors to match the rest of the label. You can set almost all the necessary properties at design-time apart from the Links.Add() piece, but here they are in code:
linkLabel1.Text = "You are accessing a government system, and all activity " +
"will be logged. If you do not wish to continue, log out now.";
linkLabel1.AutoSize = false;
linkLabel1.Size = new Size(365, 50);
linkLabel1.TextAlign = ContentAlignment.MiddleCenter;
linkLabel1.Links.Clear();
linkLabel1.Links.Add(20, 17).Enabled = false; // "government system"
linkLabel1.Links.Add(105, 11).Enabled = false; // "log out now"
linkLabel1.LinkColor = linkLabel1.ForeColor;
linkLabel1.DisabledLinkColor = linkLabel1.ForeColor;
Result:
Worked solution for me - using custom RichEditBox. With right properties it will be looked as simple label with bold support.
1) First, add your custom RichTextLabel class with disabled caret :
public class RichTextLabel : RichTextBox
{
public RichTextLabel()
{
base.ReadOnly = true;
base.BorderStyle = BorderStyle.None;
base.TabStop = false;
base.SetStyle(ControlStyles.Selectable, false);
base.SetStyle(ControlStyles.UserMouse, true);
base.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
base.MouseEnter += delegate(object sender, EventArgs e)
{
this.Cursor = Cursors.Default;
};
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x204) return; // WM_RBUTTONDOWN
if (m.Msg == 0x205) return; // WM_RBUTTONUP
base.WndProc(ref m);
}
}
2) Split you sentence to words with IsSelected flag, that determine if that word should be bold or no :
private void AutocompleteItemControl_Load(object sender, EventArgs e)
{
RichTextLabel rtl = new RichTextLabel();
rtl.Font = new Font("MS Reference Sans Serif", 15.57F);
StringBuilder sb = new StringBuilder();
sb.Append(#"{\rtf1\ansi ");
foreach (var wordPart in wordParts)
{
if (wordPart.IsSelected)
{
sb.Append(#"\b ");
}
sb.Append(ConvertString2RTF(wordPart.WordPart));
if (wordPart.IsSelected)
{
sb.Append(#"\b0 ");
}
}
sb.Append(#"}");
rtl.Rtf = sb.ToString();
rtl.Width = this.Width;
this.Controls.Add(rtl);
}
3) Add function for convert you text to valid rtf (with unicode support!) :
private string ConvertString2RTF(string input)
{
//first take care of special RTF chars
StringBuilder backslashed = new StringBuilder(input);
backslashed.Replace(#"\", #"\\");
backslashed.Replace(#"{", #"\{");
backslashed.Replace(#"}", #"\}");
//then convert the string char by char
StringBuilder sb = new StringBuilder();
foreach (char character in backslashed.ToString())
{
if (character <= 0x7f)
sb.Append(character);
else
sb.Append("\\u" + Convert.ToUInt32(character) + "?");
}
return sb.ToString();
}
Works like a charm for me!
Solutions compiled from :
How to convert a string to RTF in C#?
Format text in Rich Text Box
How to hide the caret in a RichTextBox?
Create the text as a RTF file in wordpad
Create Rich text control with no borders and editable = false
Add the RTF file to the project as a resource
In the Form1_load do
myRtfControl.Rtf = Resource1.MyRtfControlText
AutoRichLabel
I was solving this problem by building an UserControl that contains a TransparentRichTextBox that is readonly. The TransparentRichTextBox is a RichTextBox that allows to be transparent:
TransparentRichTextBox.cs:
public class TransparentRichTextBox : RichTextBox
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);
protected override CreateParams CreateParams
{
get
{
CreateParams prams = base.CreateParams;
if (TransparentRichTextBox.LoadLibrary("msftedit.dll") != IntPtr.Zero)
{
prams.ExStyle |= 0x020; // transparent
prams.ClassName = "RICHEDIT50W";
}
return prams;
}
}
}
The final UserControl acts as wrapper of the TransparentRichTextBox. Unfortunately, I had to limit it to AutoSize on my own way, because the AutoSize of the RichTextBox became broken.
AutoRichLabel.designer.cs:
partial class AutoRichLabel
{
/// <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.rtb = new TransparentRichTextBox();
this.SuspendLayout();
//
// rtb
//
this.rtb.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rtb.Dock = System.Windows.Forms.DockStyle.Fill;
this.rtb.Location = new System.Drawing.Point(0, 0);
this.rtb.Margin = new System.Windows.Forms.Padding(0);
this.rtb.Name = "rtb";
this.rtb.ReadOnly = true;
this.rtb.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
this.rtb.Size = new System.Drawing.Size(46, 30);
this.rtb.TabIndex = 0;
this.rtb.Text = "";
this.rtb.WordWrap = false;
this.rtb.ContentsResized += new System.Windows.Forms.ContentsResizedEventHandler(this.rtb_ContentsResized);
//
// AutoRichLabel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.Color.Transparent;
this.Controls.Add(this.rtb);
this.Name = "AutoRichLabel";
this.Size = new System.Drawing.Size(46, 30);
this.ResumeLayout(false);
}
#endregion
private TransparentRichTextBox rtb;
}
AutoRichLabel.cs:
/// <summary>
/// <para>An auto sized label with the ability to display text with formattings by using the Rich Text Format.</para>
/// <para>­</para>
/// <para>Short RTF syntax examples: </para>
/// <para>­</para>
/// <para>Paragraph: </para>
/// <para>{\pard This is a paragraph!\par}</para>
/// <para>­</para>
/// <para>Bold / Italic / Underline: </para>
/// <para>\b bold text\b0</para>
/// <para>\i italic text\i0</para>
/// <para>\ul underline text\ul0</para>
/// <para>­</para>
/// <para>Alternate color using color table: </para>
/// <para>{\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0 is blue.\par</para>
/// <para>­</para>
/// <para>Additional information: </para>
/// <para>Always wrap every text in a paragraph. </para>
/// <para>Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par)</para>
/// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0 is bold.\par)</para>
/// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>
/// </summary>
public partial class AutoRichLabel : UserControl
{
/// <summary>
/// The rich text content.
/// <para>­</para>
/// <para>Short RTF syntax examples: </para>
/// <para>­</para>
/// <para>Paragraph: </para>
/// <para>{\pard This is a paragraph!\par}</para>
/// <para>­</para>
/// <para>Bold / Italic / Underline: </para>
/// <para>\b bold text\b0</para>
/// <para>\i italic text\i0</para>
/// <para>\ul underline text\ul0</para>
/// <para>­</para>
/// <para>Alternate color using color table: </para>
/// <para>{\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0 is blue.\par</para>
/// <para>­</para>
/// <para>Additional information: </para>
/// <para>Always wrap every text in a paragraph. </para>
/// <para>Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par)</para>
/// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0 is bold.\par)</para>
/// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>
/// </summary>
[Browsable(true)]
public string RtfContent
{
get
{
return this.rtb.Rtf;
}
set
{
this.rtb.WordWrap = false; // to prevent any display bugs, word wrap must be off while changing the rich text content.
this.rtb.Rtf = value.StartsWith(#"{\rtf1") ? value : #"{\rtf1" + value + "}"; // Setting the rich text content will trigger the ContentsResized event.
this.Fit(); // Override width and height.
this.rtb.WordWrap = this.WordWrap; // Set the word wrap back.
}
}
/// <summary>
/// Dynamic width of the control.
/// </summary>
[Browsable(false)]
public new int Width
{
get
{
return base.Width;
}
}
/// <summary>
/// Dynamic height of the control.
/// </summary>
[Browsable(false)]
public new int Height
{
get
{
return base.Height;
}
}
/// <summary>
/// The measured width based on the content.
/// </summary>
public int DesiredWidth { get; private set; }
/// <summary>
/// The measured height based on the content.
/// </summary>
public int DesiredHeight { get; private set; }
/// <summary>
/// Determines the text will be word wrapped. This is true, when the maximum size has been set.
/// </summary>
public bool WordWrap { get; private set; }
/// <summary>
/// Constructor.
/// </summary>
public AutoRichLabel()
{
InitializeComponent();
}
/// <summary>
/// Overrides the width and height with the measured width and height
/// </summary>
public void Fit()
{
base.Width = this.DesiredWidth;
base.Height = this.DesiredHeight;
}
/// <summary>
/// Will be called when the rich text content of the control changes.
/// </summary>
private void rtb_ContentsResized(object sender, ContentsResizedEventArgs e)
{
this.AutoSize = false; // Disable auto size, else it will break everything
this.WordWrap = this.MaximumSize.Width > 0; // Enable word wrap when the maximum width has been set.
this.DesiredWidth = this.rtb.WordWrap ? this.MaximumSize.Width : e.NewRectangle.Width; // Measure width.
this.DesiredHeight = this.MaximumSize.Height > 0 && this.MaximumSize.Height < e.NewRectangle.Height ? this.MaximumSize.Height : e.NewRectangle.Height; // Measure height.
this.Fit(); // Override width and height.
}
}
The syntax of the rich text format is quite simple:
Paragraph:
{\pard This is a paragraph!\par}
Bold / Italic / Underline text:
\b bold text\b0
\i italic text\i0
\ul underline text\ul0
Alternate color using color table:
{\colortbl ;\red0\green77\blue187;}
{\pard The word \cf1 fish\cf0 is blue.\par
But please note: Always wrap every text in a paragraph. Also, different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par) and the space character behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0 is bold.\par). To escape \ or { or }, please use a leading \.
For more information there is a full specification of the rich text format online.
Using this quite simple syntax you can produce something like you can see in the first image. The rich text content that was attached to the RtfContent property of my AutoRichLabel in the first image was:
{\colortbl ;\red0\green77\blue187;}
{\pard\b BOLD\b0 \i ITALIC\i0 \ul UNDERLINE\ul0 \\\{\}\par}
{\pard\cf1\b BOLD\b0 \i ITALIC\i0 \ul UNDERLINE\ul0\cf0 \\\{\}\par}
If you want to enable word wrap, please set the maximum width to a desired size. However, this will fix the width to the maximum width, even when the text is shorter.
Have fun!
There is an excellent article from 2009 on Code Project named "A Professional HTML Renderer You Will Use" which implements something similar to what the original poster wants.
I use it successfully within several projects of us.
Very simple solution:
Add 2 labels on the form, LabelA and LabelB
Go to properties for LabelA and dock it to left.
Go to properties for LabelB and dock it to left as well.
Set Font to bold for LabelA .
Now the LabelB will shift depending on length of text of LabelA.
That's all.
I Would also be interested in finding out if it is possible.
When we couldn't find a solution we resorted to Component Ones 'SuperLabel' control which allows HTML markup in a label.
Realising this is an old question, my answer is more for those, like me, who still may be looking for such solutions and stumble upon this question.
Apart from what was already mentioned, DevExpress's LabelControl is a label that supports this behaviour - demo here. Alas, it is part of a paid library.
If you're looking for free solutions, I believe HTML Renderer is the next best thing.
A FlowLayoutPanel works well for your problem. If you add labels to the flow panel and format each label's font and margin properties, then you can have different font styles. Pretty quick and easy solution to get working.
Yeah.
You can implements, using HTML Render.
For you see, click on the link: https://htmlrenderer.codeplex.com/
I hope this is useful.

Resources