Convert code from Windows Form Application to WPF? - c#

I'm trying to convert code from a WFA (Windows Form Application) over to a WPF. However, i'm running into many difficulties. There is no .MaxLength. There is also no .Text as there is when using a Windows Form Application. How would i re-write the following code for WPF?
xbox is refering to a box on a chat window where the user types in text....
PS. The code below DOES work for WFA....
private void BoxChatAreaKeyPress(object sender, KeyPressEventArgs e)
{
var xBox = (RichTextBox) sender;
//setting a limit so the user cannot type more than 4000 characters at once
xBox.MaxLength = 4000;
if ((xBox.Text.Length > 1) && (e.KeyChar == (char) Keys.Enter))
{
WriteMessage(xBox);
}
}
private static void WriteMessage(RichTextBox xBox)
{
var writer = new StreamWriter(_client.GetStream());
String message = xBox.Text.TrimEnd('\n') + "|" + _font.Name;
writer.WriteLine(message);
writer.Flush();
xBox.Text = null;
}

This is what I came up with:
private void BoxChatAreaKeyPress(object sender, KeyEventArgs e)
{
var xBox = (RichTextBox)sender;
// Setting a limit so the user cannot type more than 4000 characters at once
var textRange = new TextRange(xBox.Document.ContentStart, xBox.Document.ContentEnd);
var textLen = textRange.Text.Trim();
if (textLen.Length <= 4000)
{
if ((textLen.Length > 1) && (e.Key == Key.Enter))
{
WriteMessage(xBox);
}
}
else
{
e.Handled = true;
}
}

Depending on the complexity of your application, it may not be straightforward directly converting from WinForm to WPF. To answer your two specific problems.
1) As you know, there's no MaxLength property on a RichTextBox in WPF. One way around this is to record the number of characters after the user has entered a character and check if it's greater than your limit. For example (from here):
private void xBox_KeyDown(object sender, KeyEventArgs e)
{
TextRange tr = new TextRange(xBox.Document.ContentStart ,
xBox.Document.ContentEnd);
if (tr.Text.Length >= 4000 || e.Key == Key.Space || e.Key == Key.Enter)
{
e.Handled = true;
return;
}
}
2) Likewise, you can use the TextRange property to get the text within an RTB:
TextRange xBoxTR = new TextRange(xBox.Document.ContentStart,
xBox.Document.ContentEnd);
string xBoxText = xBoxTR.Text;

Related

Removing spaces in MaskedTextBox on Leave Event - IP Address Validation

I'm trying to do IPv4 validation in a maskedtextbox. My mask is set to ###.###.###.### and i have my Key Down Event handling the '.' key as going to next octet which works great... However, if an IP address dows not have 3 digits in each octet i get random spaces when I grab the textfield for use.
For example: if I type 72.13.12.1 the output is "72 .13 .12 .1" <- I don't want the spaces.
I've tried doing some validation like removing the spaces once I leave the maskedtextbox, but if I remove the spaces, my mask kicks back in and changes it to "721.321.1 ."
this.maskedTextBoxExternIP.ResetOnSpace = false;
this.maskedTextBoxExternIP.SkipLiterals = false;
this.maskedTextBoxExternIP.PromptChar = ' ';
this.maskedTextBoxExternIP.Mask = "###.###.###.###";
this.maskedTextBoxExternIP.ValidatingType = typeof(System.Net.IPAddress);
this.maskedTextBoxExternIP.KeyDown += new KeyEventHandler(this.maskedTextBoxExternIP_KeyDown);
this.maskedTextBoxExternIP.Enter += new EventHandler(this.maskedTextBoxExternIP_Enter);
this.maskedTextBoxExternIP.Leave += new EventHandler(this.maskedTextBoxExternIP_Leave);
private void maskedTextBoxExternIP_Leave(object sender, EventArgs e)
{
// Resets the cursor when we leave the textbox
maskedTextBoxExternIP.SelectionStart = 0;
// Enable the TabStop property so we can cycle through the form controls again
foreach (Control c in this.Controls)
c.TabStop = true;
IPAddress ipAddress;
if (IPAddress.TryParse(maskedTextBoxExternIP.Text, out ipAddress))
{
//valid ip
}
else
{
//is not valid ip
maskedTextBoxExternIP.Text = maskedTextBoxExternIP.Text.Replace(" ", string.Empty);
}
}
// Handle the Enter event
private void maskedTextBoxExternIP_Enter(object sender, EventArgs e)
{
// Resets the cursor when we enter the textbox
maskedTextBoxExternIP.SelectionStart = 0;
// Disable the TabStop property to prevent the form and its controls to catch the Tab key
foreach (Control c in this.Controls)
c.TabStop = false;
}
// Handle the KeyDown event
private void maskedTextBoxExternIP_KeyDown(object sender, KeyEventArgs e)
{
// Cycle through the mask fields
if (e.KeyCode == Keys.Tab || e.KeyCode == Keys.OemPeriod || e.KeyCode == Keys.Decimal)
{
int pos = maskedTextBoxExternIP.SelectionStart;
int max = (maskedTextBoxExternIP.MaskedTextProvider.Length - maskedTextBoxExternIP.MaskedTextProvider.EditPositionCount);
int nextField = 0;
for (int i = 0; i < maskedTextBoxExternIP.MaskedTextProvider.Length; i++)
{
if (!maskedTextBoxExternIP.MaskedTextProvider.IsEditPosition(i) && (pos + max) >= i)
nextField = i;
}
nextField += 1;
// We're done, enable the TabStop property again
if (pos == nextField)
maskedTextBoxExternIP_Leave(this, e);
maskedTextBoxExternIP.SelectionStart = nextField;
}
}
#madreflection I finally got the IPAddressCrontrolLib to work I just used the source files and embedded the library that way. Had to do a little fudging around to clear all the errors that we there. All good now! Just needed a new day to get through that one. Thanks for your help.

Using function in ASP.NET web application

Excuse me guys, i'm a beginner in c# and needed help and some guidance in creating a calculator web app.
So i was given a task to create a calculator web app using the ASP.NET web application web form with the UI looking like this:
Calculator UI
The thing is, i made a mistake and made it using Windows Forms App (WFA) instead and i could get the calculator to work.
But when i tried to make the calculator using the ASP.NET web application web form the calculator won't work because somehow the variable that i set to run the method didn't get any value unlike when i run it in the WFA.
Here is my code:
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
bool lastpressedIsOperation;
string input = String.Empty;
protected void num_Click(object sender, EventArgs e)
{
Button button = sender as Button;
//this.display.Text = "";
input+=button.Text;
if (display.Text == "0" && display.Text != null)
{
display.Text = button.Text;
}
else
{
display.Text += button.Text;
}
}
protected void op_Click(object sender, EventArgs e)
{
Button button = sender as Button;
input+=button.Text;
if (display.Text == "0" && button.Text == "-" && display.Text != null)
{
display.Text = button.Text;
}
else
{
display.Text += button.Text;
}
}
protected void del_Click(object sender, EventArgs e)
{
//this.display.Text = input.ToString(0,input.Length);
}
protected void del_all_Click(object sender, EventArgs e)
{
this.display.Text = "0";
this.input = string.Empty;
}
private void enter_Click(object sender, EventArgs e)
{
string inFix = input;
string isValid = Validate(inFix);
string rpn = ConvertToPostFix(isValid);
string result = Convert.ToString(CalculateRPN(rpn));
this.display.Text = result;
input = result;
}
private static string Validate(string inFix)
{
StringBuilder newstring = new StringBuilder(inFix);
Stack<int> lb_index = new Stack<int>();//stack for left bracket index
Queue<int> rb_index = new Queue<int>();//stack for right bracket index
char temp = '#';
Console.WriteLine("temp: ", temp);
for (int i = 0; i < newstring.Length; i++)
{
if (newstring[i] == '(')
lb_index.Push(i);
else if (newstring[i] == ')')
rb_index.Enqueue(i);
Console.WriteLine("temp: {0}", temp);
if (newstring[i] == '-')//change unary - to ~
{
if (temp.IsOperator())
{
newstring[i] = '~';
}
}
temp = newstring[i];
}
if (lb_index.Count == rb_index.Count)
{
bool bracket_valid = true;
for (int i = 0; i < lb_index.Count; i++)
{
if (lb_index.Pop() > rb_index.Dequeue())
{
bracket_valid = false;
break;
}
}
if (bracket_valid != true)
{
newstring.Clear();
newstring.Append("Error, Bracket wrong");
}
}
else if (lb_index.Count < rb_index.Count || lb_index.Count > rb_index.Count)
{
newstring.Clear();
newstring.Append("Error, Bracket wrong");
}
Console.WriteLine("newstring = {0}", newstring);
return newstring.ToString();
}
The idea is i want to get the string from textbox after the user inputted the value using number and operation buttons and pressed the enter button.
The string is then validated first using Validate(inFix), then formatted into postfix ConvertToPostFix(isValid), which then calculated using CalculateRPN(rpn).
But i dont know why the isValid variable never get the value from Validate(inFix) which cause the other methods not working. Is there some difference on how to use the function in ASP Web app form? If so, how do i use method/function in this?
And is there any better way to implement this so i can fulfill my task?
I believe your problem is that you are setting:
string inFix = input;
In your
enter_Click
method.
Yet, the
input
variable is initialized to:
string input = String.Empty;
So, each time the form is loaded, i.e. on an initial load or a postback, the input variable is re-initialized to an empty string.
I'll not reinvent the post here, but to resolve this, you need to do something like:
Session["INPUT"] = input;
whenever input is modified, and do something like:
input = (string)Session["INPUT"];
To initialize the input variable on the page load.
If it is the initial page load, the input variable will be null (i.e. the session variable Session["INPUT"] does not exist).
Basically, what I am saying is that, while the asp.net session stores the state of controls on the forms, it does not save the state of your own class variables that you add to the page.

finding Textbox cursor position,line no. and column no. in asp.net

I am a beginner to web application development. I have the code of a windows application. Same functionality i have to convert into a web application. I have a text box control. I am loading some text to that text box. I want to find the current cursor position, line number and column number. The code for the windows application is below:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = #"This is a demo for text box control
I am trying to find the cursor position ,
line no and column no
of the cursor.";
}
private void textBox1_Click(object sender, EventArgs e)
{
textBox1.SelectionStart++;
label2.Text = textBox1.SelectionStart.ToString();
int i = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);
label3.Text = i.ToString();
int j =textBox1.SelectionStart - textBox1. GetFirstCharIndexFromLine(i);
label4.Text = j.ToString();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Up) || (e.KeyCode == Keys.Right) ||
(e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Down))
{
textBox1.SelectionStart++;
label2.Text = textBox1.SelectionStart.ToString();
int i = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);
label3.Text = i.ToString();
int j = textBox1.SelectionStart -
textBox1.GetFirstCharIndexFromLine(i);
label4.Text = j.ToString();
}
}
as the accepted answer in this post, you have to use javascript to get the SelectionStart and SelectionEnd in your clinet side. then, post the result (may be using a hidden input value) to the server with the reset of data:
How to get selected text from textbox control with javascript

Check window for focus-Password Generator C#

For my end of year project I am creating a password generator where you generate a password, then you can choose whether or not you want to store it in a local compact DB(.sdf). I am working on the GUI at the moment. I am creating a strength bar for passwords but the problem is that I can't seem to have it update the strength bar without first moving the slider. Let me show you example of what I am talking about. I was wondering if I could do this with code or with action events. Tell me what you think. Below is some code for the GUI designer. Do you think this is a good idea or would there be a better way? The focus idea came from if the window has focus it would keep checking the options and see if anything has changed. Video: http://youtu.be/ihSeKbsL55M
namespace PasswordGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void fileToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void bcopy_Click(object sender, EventArgs e)
{
if (passwordGenBox.Text.Length != 0)
{
Clipboard.SetText(passwordGenBox.Text);
}
else
{
MessageBox.Show("No Password Generated.", "Copy Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void bclear_Click(object sender, EventArgs e)
{
passwordGenBox.Text = "";
}
private void lengthSlider_Scroll(object sender, EventArgs e)
{
sliderLength.Text = lengthSlider.Value.ToString();
int str = lengthSlider.Value;
bool scheck = symCheck.Checked;
bool ncheck = numbersCheck.Checked;
//1-10 no symbols or numbers
if (str > 0 && str <= 10)
{
strLabel.Text = "Week";
}
//1-10 symbols no numbers
if (str > 0 && str <= 10 && scheck == true && ncheck == false)
{
strLabel.Text = "Alright";
}
//1-10 no symbols but numbers
if (str > 0 && str <= 10 && scheck == false && ncheck == true)
{
strLabel.Text = "Week";
}
//1-10 symbols & numbers
if (str > 0 && str <= 10 && scheck == true && ncheck == true)
{
strLabel.Text = "Okay";
}
}
private void bgen_Click(object sender, EventArgs e)
{
int pwlength = lengthSlider.Value;
bool symbols = false;
bool numbers = false;
if (symCheck.Checked && numbersCheck.Checked)
{
symbols = true;
numbers = true;
}
else if (symCheck.Checked && numbersCheck.Checked == false)
{
symbols = true;
numbers = false;
}
else if (symCheck.Checked == false && numbersCheck.Checked)
{
symbols = false;
numbers = true;
}
else
{
symbols = false;
numbers = false;
}
Generator gen = new Generator(pwlength, symbols, numbers);
}
}
}
Well, it's quite difficult to understand what you're actually asking here but the reason your ProgressBar isn't updating is that you're not actually telling it to update unless you move the slider.
Notice how you have all your logic for whether the password is "alright, weak or okay" on the Slide event of your "lengthSlider" component. However, nowhere in that code do you set the value of the ProgressBar - that appears to be done on the "bgen_Click" event which I assume is the generate password button?
In order to update the GUI when you operate the individual controls you need to call the appropriate code. I would suggest you put all your logic into meaningful functions and call them as needed.
Personally I'd have something along these lines:
GetPasswordStrengthString(); - check for symbols and numbers checkbox.checked and the length to return an appropriate string for the "strLabel" label.
CalculateStrengthBarLength(); - all your logic to determine the length of the ProgressBar
These would then be called wherever you want them to take effect. For example, on the CheckedChanged event of the symbols and numbers checkboxes as when that changes you want to see it reflected in the ProgressBar.

Autocomplete AND preventing new input - combobox

How can I allow the users of my program to type in a value and have it auto-complete, however, I also what to prevent them from entering new data because it would cause the data to be unfindable (unless you had direct access to the database).
Does anyone know how to do this?
The reasoning behind not using just a dropdown style combobox is because entering data by typing it is and then refusing characters that are not part of an option in the list is because it's easier on the user.
If you have used Quickbook's Timer, that is the style of comboboxes I am going for.
Kudos to BFree for the help, but this is the solution I was looking for. The ComboBox is using a DataSet as it's source so it's not a custom source.
protected virtual void comboBoxAutoComplete_KeyPress(object sender, KeyPressEventArgs e) {
if (Char.IsControl(e.KeyChar)) {
//let it go if it's a control char such as escape, tab, backspace, enter...
return;
}
ComboBox box = ((ComboBox)sender);
//must get the selected portion only. Otherwise, we append the e.KeyChar to the AutoSuggested value (i.e. we'd never get anywhere)
string nonSelected = box.Text.Substring(0, box.Text.Length - box.SelectionLength);
string text = nonSelected + e.KeyChar;
bool matched = false;
for (int i = 0; i < box.Items.Count; i++) {
if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().StartsWith(text, true, null)) {
matched = true;
break;
}
}
//toggle the matched bool because if we set handled to true, it precent's input, and we don't want to prevent
//input if it's matched.
e.Handled = !matched;
}
This is my solution, I was having the same problem and modify your code to suit my solution using textbox instead of combobox, also to avoid a negative response after comparing the first string had to deselect the text before comparing again against autocomplet list, in this code is an AutoCompleteStringCollection shiper, I hope this solution will help
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
String text = ((TextBox)sender).Text.Substring(
0, ((TextBox)sender).SelectionStart) + e.KeyChar;
foreach(String s in this.shippers)
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()) ||
e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
return;
e.Handled = true;
}
OK, here's what I came up with. Hack? Maybe, but hey, it works. I just filled the combobox with the days of the week (hey, I needed something), and then handle the keypress event. On every key press, I check if that word matches the begining of any word in the AutoCompleteSourceCollection. If it doesn't, I set e.Handled to true, so the key doesn't get registered.
public Form5()
{
InitializeComponent();
foreach (var e in Enum.GetValues(typeof(DayOfWeek)))
{
this.comboBox1.AutoCompleteCustomSource.Add(e.ToString());
}
this.comboBox1.KeyPress += new KeyPressEventHandler(comboBox1_KeyPress);
}
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string text = this.comboBox1.Text + e.KeyChar;
e.Handled = !(this.comboBox1.AutoCompleteCustomSource.Cast<string>()
.Any(s => s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()))) && !char.IsControl(e.KeyChar);
}
EDIT: If you're on .Net 3.5 you'll need to reference System.Linq. If you're on .NET 2.0 then use this instead:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string text = this.comboBox1.Text + e.KeyChar;
foreach (string s in this.comboBox1.AutoCompleteCustomSource)
{
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()))
{
return;
}
}
e.Handled = true;
}
I know I'm about six years late but maybe this can help somebody.
private void comboBox1_Leave(object sender, EventArgs e)
{
if (comboBox1.Items.Contains(comboBox1.Text)) { MessageBox.Show("YE"); }
else { MessageBox.Show("NE"); }
OR
if (comboBox1.FindStringExact(comboBox1.Text) > -1) { MessageBox.Show("YE"); }
else { MessageBox.Show("NE"); }
}

Categories