How to make password box non-editable in wpf - c#

I need to make password box as non-editable in wpf.
I used
IsEnabled = false
But it is affecting my style some blur effect came because of that...
Is there any other way to achieve this ?

I know this is two years old, but I had the same need and solved it this way:
The combination of these two properties, both set to false, will prevent entry/editing in the control, w/o affecting your desired style:
Focusable, IsHitTestVisible

You can handle the PreviewTextInput event, preventing the user from entering text. Like so:
Xaml:
<PasswordBox PreviewTextInput="HandleInput"/>
Codebehind:
private void HandleInput(object sender, TextCompositionEventArgs e) {
e.Handled = true;
}

One solution is to make a custom functionality to mimic the IsReadOnly.
There are couple things to take care of - e.g. clipboard pasting
also.
You'll get similar behavior by defining some attached property (e.g. IsPasswordReadOnly or just the same) - which would work out all that's required.
Here is a good starting example - which could, should I think work for Password box as well - but I haven't tried it and you gotta test yourself.
Readonly textbox for WPF with visible cursor (.NET 3.5)
You'd have to replace references to TextBox with PasswordBox, rename it to IsReadOnly - and I think the rest might work the same.
And you use it like...
<PasswordBox my:AttachReadOnly.IsReadOnly="True" />

Pretty simple..
Set an event handler for PreviewTextInput in your XML like so:
PreviewTextInput="PasswordBoxOnPreviewTextInput"
And within that method:
private void PasswordBoxOnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (m_DisablePasswordBox)
e.Handled = true;
}
It will now prevent you from typing anything in :)

Related

UWP: Binding + TextChanging = JIT win32 exception

I am 100% sure I am doing this the wrong way and this problem is "by design".
I want to have a Slider and a TextBox that displays its value. The user can either use the Slider, or manually enter a number in the TextBox.
I also wanted to take advantage of the TextChanging event to ignore any non-numerical entries. TextChanged would only function after a user has entered something and it's not a preferable scenario, and KeyDown would not capture other methods of input like ink or speech.
So I have this:
<StackPanel>
<Slider x:Name="Size" Value="100" Maximum="100" Minimum="0" />
<TextBox x:Name="SizeText" Text="{Binding ElementName=Size,Path=Value,Mode=TwoWay}" TextChanging="SizeText_TextChanging" />
</StackPanel>
Where "SizeText_TextChanging" is simply an empty block of code right now:
private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
// Nothing Here.
}
This code builds, but at startup the app throws a JIT unhandled win32 exception and closes.
Changing TextChanging to TextChanged works fine, but again I prefer to get TextChanging to work (or something similar) to give a better user experience.
"Mode" also has no effect. I tried all three different Modes, all crash. By removing the binding altogether and giving the Text property any value works fine.
I also thought that maybe having the TextChanging event handler empty is the problem, so I borrowed the code below from here but the app still crashes:
private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
if (!Regex.IsMatch(sender.Text, "^\\d*\\.?\\d*$") && sender.Text != "")
{
int pos = sender.SelectionStart - 1;
sender.Text = sender.Text.Remove(pos, 1);
sender.SelectionStart = pos;
}
}
Like I said, I am probably approaching this the wrong way. I am just starting to learn UWP and C# so I am a total noob. But I have read everything I could about TextChanging and it simply talks about rendering the value and the associated cautions of what not to write within the TextChanging event. So while it sounds like the app is being thrown into a loop trying to read the value of the slider and trying to see what the TextChanging event says, I don't see how to fix it. Please help!
Thank you
I don't know why this is happening, but a workaround is to register the TextChanging event handler only once SizeText (or the page) has loaded and using x:Bind instead of Binding:
XAML
<TextBox x:Name="SizeText" Text="{x:Bind Size.Value, Mode=TwoWay}" Loaded="SizeText_Loaded"/>
CS
private void SizeText_Loaded(object sender, RoutedEventArgs e)
{
SizeText.TextChanging += SizeText_TextChanging;
}
private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
}
I meet the same problem but this solution doesn't works for me.
As #Mushriq, I use _TextChanging() to ignore any non-numerical entries in a form.
But my form contains a lot of numeric fields and also a master-detail part, which contains 2 of these fields.
The problem is that I enter in the _Loaded the first time that I display a part, but not for the other parts. When I display existing parts there is no problem, but if I add a new part I get the exception.
Is there a way to adapt the solution to my case?

Locked property is not working in Windows Forms for Textbox

When I select Locked property to true for Textbox in Windows Forms. On runtime I will be able to type into that Textbox
So how to can I make it readonly without disabled effect or without using ReadOnly property of Textbox
Could someone please help me on this? Thanks in advance.
The Locked property is a design-time only property. It is useful to avoid accidental changes while you are designing the form. When turned on, you see a little lock icon on the control and there's nothing you can do to accidentally change any of the control's properties.
But no, the control itself doesn't actually have that property. It was added by the designer. So it cannot have any effect at runtime. There are other properties like that, such as Modifiers and Language. Only useful for their side-effects at design-time.
Making a TextBox read-only at runtime is most easily implemented by setting its ReadOnly property to True. If you want to do this at design-time then there's a very strong hint that you ought to use a Label instead.
try this
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}

Remove dotted line on button

How do you remove the dotted line that appears on buttons when they are selected (either via tab or by clicking them)?
This question is for winforms - any help is appreciated.
Edit: I apologize for the duplicate question. I did search for an answer, but I did not know this issue was due to the 'focus' of the button. As I result I was not finding the appropriate answers.
This happens because your Button gains focus. It is possible to remove it but that means giving the focus to something else when your button's focus Enter event is triggered.
private void button1_Enter(object sender, EventArgs e)
{
// give focus to something else
}
The problem with that is that you lose the ability to use the keyboard in order to select the button (using tab).
Moreover, a more correct approach would be to give focus to the last control that had focus instead of passing it fixed one.
have you tried to remove the focus from the button.
just call Focus(); when the button is clicked.
create custom control add ShowFocusCues and build to use
Example
public class button : System.Windows.Forms.Button
{
protected override bool ShowFocusCues
{
get
{
return false;
}
}
}
Look for button border settings.
I do not get this border, if I set the BorderSize to 0 in the FlatAppearance section
From Remove button border on tab c# winforms
You can set the ShowFocusRectangle peoperty to false.
The only answer here that really works without having to hack (moving focus to another control) is Wongsathon Tuntanakan's answer.
I refer to his answer and, as a bit of extra, I've converted his code to VB:
Public Class YourButtonClass
Inherits System.Windows.Forms.Button
Protected Overrides ReadOnly Property ShowFocusCues As Boolean
Get
Return False
End Get
End Property
End Class

TextBox that Gets the value of another TextBox VISUAL C#

Is It possible that if I create two TextBoxes.
When the first TextBox is modified from input, the second text box is set to be read only and its value will update depending on what you had written in the first text box.
It's like when I am posting here in stackoverflow there is also a read only area that follows what I'm typing (The preview window). :)) Thanks!!!
If it's win-form application, it's so simple. try this :
private void txtFirstTextBox_TextChanged(object sender, EventArgs e) {
if (string.IsNullOrEmpty(txtFirstTextBox.Text)) {
txtSecondTextBox.Clear();
return;
}
txtSecondTextBox.Text = txtFirstTextBox.Text;
}
hope this help.
I should note: This is a solution if you're using WPF for your UI.
Yes that's easily possible if you have, for example the first textbox:
<TextBox x:Name="FirstBox"/>
You can bind to this text box's content via:
<TextBox x:Name"SecondBox" Text="{Binding ElementName="FirstBox", Path="Text", UpdateSourceTrigger=PropertyChanged}" IsEnabled="False"/>
And when the first text box changes, the second one should follow suit. This is all handled automatically for you via binding, it connects to the Text property on the TextBox named "FirstBox". This second TextBox is disabled by setting the IsEnabled property to "False"
Since there is already a WPF Solution and you didn't specify which you are using, I'll go ahead and post a WinForms solution.
Luckily, this is relatively simple in WinForms as well. You simply wire a TextChanged event handler for the first text box which updates the text of the second:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = ((TextBox)sender).Text;
}

How to inherit base Textbox to provide colored borders

I have a winform app that we use in house. It has many individual controls on each of it's 25 "pages"(usercontrols). Our user base prefers very technicolor apps...they want a TextBox to be outlined Blue if it is a required field (color should go away if data entered). They want a TextBox to change to outlined Green if data has been changed in it to remind them to save. They want a currently highlighted TextBox to be outlined RedOrange.
I have been trying to come at this from many different angles (some of you have probably seen similar posts by me lately). Non of them work... So one way I KNOW will work is to register the paint event for every control and check for a "required" tag for the required portion. The OnFocus for the current field portion and finally the Validate event for the data changed portion.
I know this is not the best way or at least I STRONGLY suspect it isn't but I am out of time, nearly, and nearing my point of frustration. That being said, will that DESTROY my app's responsiveness? Is there a better way? Can I override the base control to color on different premises so that I don't have to go to each of the 100+ controls?
Any idea would be welcome because I am between my stupid Paint_Event idea and rewriting all the controls in WPF... :)
I will be rewarding a solution that works for me and that I can implement shortly with a Bounty.
I am so sick of colors...
Here is my attempt based on suggestions.
public class MyTextBox : TextBox
{
private bool _isRequired;
public bool isRequired
{
get
{
return _isRequired;
}
set
{
_isRequired = value;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (isRequired && base.Text.Equals(string.Empty))
{
HighlightControl(e.Graphics);
}
}
private void HighlightControl(Graphics graphics)
{
ControlPaint.DrawBorder(
graphics,
this.ClientRectangle,
Properties.Settings.Default.RequiredFieldColor,
Properties.Settings.Default.BorderWidth,
Properties.Settings.Default.BorderStyle,
Properties.Settings.Default.RequiredFieldColor,
Properties.Settings.Default.BorderWidth,
Properties.Settings.Default.BorderStyle,
Properties.Settings.Default.RequiredFieldColor,
Properties.Settings.Default.BorderWidth,
Properties.Settings.Default.BorderStyle,
Properties.Settings.Default.RequiredFieldColor,
Properties.Settings.Default.BorderWidth,
Properties.Settings.Default.BorderStyle);
}
}
I don't know the particulars of your app, but you could derive your own control from the base TextBox and let it handle much of this for you. Some thoughts:
Give it a bool Required property and some internal logic to color accordingly.
Have the textbox respond to its own
events - when text is entered, it can
do the right thing - change colors or
whatever is appropriate.
Provide your derived control with
properties to set the colors that get
used for each condition, then you can
switch them easily when the users
decide they want pink rather than
green.
You can utilize the focus events to "know" whether your TextBox (this is the one control you mentioned, so I'll assume this is the main control used here) has focus or lost it and the text change events can be used to drive all the color changes to the control.
You can certainly wire up all the
text boxes to control the
Apply/OK/whatever buttons to
determine if the buttons should be
enabled, assuming you have an Apply button or something like that which stores the data on click. There are a number of ways to communicate this. It's easy enough to iterate through the controls and ask their state.
Seems like this would work just fine.
What have you tried? You didn't really mention what you'd tried that didn't work.
You've got a problem, TextBox is, erm, special. Windows Forms leaves all painting to the native Windows EDITBOX control, the Paint event won't be raised. That can be fixed by setting the UserPaint control style to true:
using System;
using System.Drawing;
using System.Windows.Forms;
class MyTextBox : TextBox {
public MyTextBox() {
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
// Paint something
//...
}
}
Copy and paste this into a new class, compile and drop the new control from the top of the toolbox. Try it out, you'll be quite disappointed. What you see is the result of close to 20 years of appcompat hacks on a control that dates back to Windows version 2. One of the grave crimes that EDITBOX commits is painting itself without generating a WM_PAINT message. That was important way back when Windows had to run on a 386SUX, keeping it compatible with old programs prevented Microsoft from fixing its behavior.
No happy answers here, you'll have to give up on the idea of customizing the border. What you can do is give the control a distinct BackColor when it has the focus. For example:
class MyTextBox : TextBox {
Color mBackColor;
protected override void OnEnter(EventArgs e) {
mBackColor = base.BackColor;
base.BackColor = Color.AliceBlue;
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e) {
base.BackColor = mBackColor;
base.OnLeave(e);
}
}
You can inherit from base control classes and add your own drawing logic. That won't be very expensive performance-wise, but, if your app is of significant size, you'll have to replace each occurence of standard TextBox with your own implementation.

Categories