HtmlElementEventArgs KeyPressedCode Confusion - c#

I'm using the following code to decide if a '.' (full stop) has been entered into a webbrowser control:
private void body_KeyUp(object sender, HtmlElementEventArgs e)
{
if (e.KeyPressedCode == '.')
{
// Do something
}
}
According to msdn KeyPressedCode returns an ASCII value. What I get by breakpointing is '190' if I enter a '.' however. This is not even listed in the standard ASCII table.
Obviously I could simply test for 190 but I fear that KeyPressedCode might return different values on different systems with different code pages, languages and so on.
So can you please explain me why KeyPressedCode returns '190' instead of '46' and how I can manage this problem 'safely'?
Interestingly enough the return value for ' ' (space) is always correct ('32').
Playing with System.Text.Encoding.GetEncoding and different code pages didn't solve the problem, I don't have much experience with code pages however.

You were likely using a wired keyboard, because keycode 190 is an OEM number keycode of .. If you were using a laptop it would behave as you expected.

Just a wild guess, but have you checked the values of e.AltKeyPressed , e.CtrlKeyPressed and e.ShiftKeyPressed ? Hope you see what I'm getting at...

Related

C# Check if contains various combination of substring

I want to check If my OCR result (a string) is either "No Edge" or "No Signal".
Problem is sometimes I would get N0 Edge, No Signa1, N0 signa1, No 5ignal, etc. The letter o, S, i and l can sometimes become digits or something else. Unfortunately there is nothing else I can do regarding the OCR.
Currently I am doing this:
ocrResult = ocrResult.ToLower();
if (ocrResult.Contains("edg") || ocrResult.Contains("gna"))
{
//no edge or no signal
}
else
{
//Not no edge or no signal
}
Can any of you please suggest a smarter approach?
There's a library called Simila which is designed for such scenarios:
In Simila you can have this:
// A similarity engine which accepts similar if similarity is more than 70%
var simila = new Simila() { Treshold = 0.7 };
if (simila.AreSimilar(ocrResult, "No Edge") || simila.AreSimilar(ocrResult, "No Signal"))
{
// ...
}
A simple documentation of Simila is available here:
https://github.com/mehrandvd/Simila/wiki
FYI, I'm working on it and it is still in beta version. Let me know if an early release helps you, so I can create an early beta release for you.
If what you are doing works just keep doing it, it's simple, easy to understand and scanning a 9 letter string twice isn't likely to cause performance issues unless you have really big data sets.
Just add a comment so that someone who looks at this code years from now know why you are looking for seemingly random substrings.
If this isn't working then what you are looking for is a "classification algorithm" (Wikipedia list's 79 of them) - but they can get complex and choosing the right one can be tricky so they truly an overkill if simple string comparison does the job.
Well the .lower is slower then a comparison that ignores the case. Certainly if u use it in a loop. So at first i recommend you do a comparison that ignores the case. For readability and maintainability i advice u refactor the comparison. And finally u should check if the string is empty or null, then u do not have to compare the string.
Example:
if (IsThereNoEdgeOrNoSignal(ocrResult))
{
//no edge or no signal
}
else
{
//Not no edge or no signal
}
private static bool IsThereNoEdgeOrNoSignal(string ocrResult)
{
if (string.IsNullOrEmpty(ocrResult))
return false;
return ocrResult.IndexOf("edg", StringComparison.CurrentCultureIgnoreCase) >= 0 || ocrResult.IndexOf("gna", StringComparison.CurrentCultureIgnoreCase) >= 0;
}
if it only stays to these two strings, then you should keep it this way, does it grows with more possibilities you should check it with a regular expression.
I hope this helps u.

Trap NULL key in WPF application

I am using a barcode scanner and we were looking for a way to determine if input was from a keyboard or the scanner. The input will be used in a WPF POS application. We thought we had come up with a good method by using the scanners ability to prefix reads with custom characters. The first character ideally would be non printable so we chose NULL or '\0'. We used the following code to register an event handler
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.Control), System.Windows.Controls.Control.KeyUpEvent, new RoutedEventHandler(KeyUpEvent));
internal static void KeyUpEvent (object sender, RoutedEventArgs e)
{
KeyEventArgs keyEvent = e as KeyEventArgs;
if (keyEvent != null)
{
keyEvent.Key.ToString();
}
}
This however seems to not get the first NULL character and instead moves to the next char which is the length of the data.
I have also tested with a console app and just done a Console.ReadKey(). This returns me the null char as the first thing read so I know the scanner is definitely sending the correct data.
So is there any way in WPF to obtain all the data read?
Edit:
I tried using TextCompositionEventHandler but to no avail, i still only get the printable characters coming through.
KeyEventArgs.Key is not a character, it's an enum indicating which key was pressed. There is no NULL keyboard key so there is no point trying to check for the ASCII NULL (0x00) character. Moreover, most non-printable characters have no equivalent key and require the user to use a combination of keys to type them.
If you want to detect scanner codes using prefixes, try chekcing the UIElement.TextInput TextBoxBase.TextChanged events.
A better idea may be to use the scanner's SDK (if available) to send data directly to your application. More expensive models usually have an SDK to communicate with applications directly instead of emulating the keyboard.
I might be wrong, but I don't think NULL and \0 is the same in this context. Have a look at this post. They suggest using TextInput instead of KeyUp.
How to get KeyChar in WPF application

detect un-english formats

i am working with a winform application , and in the richbox_textchange i would like to detect whether the entered text is English or not because if it is english i`ll perform LeftToRight typing else RightToLeft typing .
I used that code :
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (CultureInfo.CurrentCulture.TextInfo.IsRightToLeft)
{
label1.Text = "RTL";
}
else
{
label1.Text = "LTR";
}
}
but i always get : LTR only , label1 never change text to RTL even if i typed arabic !!!
EDIT : ANSWERED !!
Firstly Thanks to everybody for helping me here and especially Oded , here is the solution i could figure out
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (InputLanguage.CurrentInputLanguage.Culture.TextInfo.IsRightToLeft)
{
label1.Text = "RTL";
}
else
{
label1.Text = "LTR";
}
}
You need to add the correct namespace to the top of your class:
using System.Globalization;
At this point the CultureInfo and TextInfo classes will be available directly.
Update:
It appears that you are trying to find out the current input language. Take a look at the InputLanguage class and its methods. It is in the System.Windows.Forms namespace.
InputLanguage.CurrentInputLanguage.Culture.TextInfo.IsRightToLeft
The problem is that CultureInfo.CurrentCulture.TextInfo.IsRightToLeft is returning information about the current system setting, not the specific text that was typed into the textbox.
It has no idea if you've typed English, or Arabic, or Cyrillic into the textbox, and it doesn't care. All it cares about is what your computer is configured to display, that's why it never changes.
Unfortunately, I don't believe it's possible to obtain the language of a particular string of text. You might have some luck with the Text.EncodingInfo.CodePage property, but it's unlikely that anything will tell you the language of text with absolute certainty. Another possible approach is to iterate through the characters in the string, checking them for information. Something like that is described here.
All things considered, it's probably better to just ask the user. What do other applications do that support multiple input languages?

C# how to do <enter> on barcode?

I have a combination of ItemNo and LotNo value.
Example :
ItemNo: I123
LotNo : L12345
Barcode Value is: "I123L12345"
I want to put the value of ItemNo to txtItemNo.Text and LotNo to txtLotNo.Text
How can I instruct the barcode to do Carriage Return or Enter so that I can be able to input 2 values on one Barcode scan.
My barcode supports CODE 128, CODE 3of9 and CODE 93.
Thanks in advance.
It sounds like you want to have the barcode automatically insert an EnterKey within the scanned value. Although there may be barcode scanners out there that would do this, most will not.
Instead, it's up to your code to recognize that the entered value has two values within it, and to parse them out and disseminate them to their appropriate fields.
For example, if each code starts with a letter, followed by a numeric value, then can walk through the characters, checking for alpha or numeric, and deal with them accordingly.
You can put a TAB character (0x09) between the 2 parts in your barcode and make sure that your text boxes have consecutive TabIndex and AcceptTabs set to false. So when the barcode reader puts the tab into the first text box the focus will move to the second box.
I have worked with Barcodes Readers (Datalogic and Symbol) for almost 3 years and what you are asking is a matter of Barcode Reader Configuration.
You will probably have to read codes from you configuration Chart and set after the BARCODE is read send CR as well.
provide us the Brand and Model and maybe I can help you set that up.
programatically of course that you can listen to the Text Event (on text change) and when you have the Barcode lenght just move the Focus() to other control, or add a NewLine (if it's a Multiline TextBox for example...
private void txtMyBCInput_OnTextChanged(...) {
if(txtMyBCInput.Length >= 13)
txtMyBCInput.Text += System.Environment.NewLine;
}
I tried to send them an email requesting technicall data for your issue, I got this:
Dear Bruno, According to our sales policy, we support our customer
through our local partner. Please let us know where (Company name) your
friend got our device, and I will contact the company to help your
friend. If you have any queries, please let me know.
Thank you!
Sincerely yours,
Julee Lee
Overseas Sales EMEA Division/Sales Manager
Bluebird Soft Inc.
1242 Gaepo-dong, Kangnam-gu, Seoul, Korea
Tel: 82-70-7730-8130 Mobile: 82-10-8876-6564 Fax: 82-2-548-0870
So, please fell free to contact them and ask for this feature :)
This workaround might help :
First , you have to include delimiters to your barcode.
Then use this code (This code assumes the delimiter is '$') :
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Contains("$"))
{
string[] str_split = textBox1.Text.Split("$".ToCharArray ());
textBox1.Text = str_split[0].ToString ();
textBox2.Text = str_split[1].ToString();
}
}
If you are printing the barcode yourself, you can use Code128 and include a CR, LF, and or TAB in the barcode. BTW, you should take a look at GS1-128, since you are doing something that looks like a proper application of GS1-128. Doing that would allow your business partners to use your barcodes without having to negotiate the format, as long as their software understands GS1-128.

C# parse string "0" to integer

I have a new laptop at work and code that worked earlier in the week does not work today.
The code that worked before is, simplified:
while (dr.Read())
{
int i = int.Parse(dr.GetString(1))
}
Now it fails when the database value is 0. Sometimes, but not reliably, this will work instead:
while (dr.Read())
{
int i = Convert.ToInt32(dr["FieldName"]))
}
Am I missing something stupid?
Oddly enough, ReSharper is also having tons of weird errors with the same error message that I am getting with the above code: "input string was not in the correct format." (Starts before I even load a project.)
Any ideas? Anyone having any SP issues? I did try to make sure all my SPs were up-to-date when I got the machine.
EDIT: I understand how to use Try.Parse and error-handling. The code here is simplified. I am reading test cases from a database table. This column has only 0, 1, and 2 values. I have confirmed that. I broke this down putting the database field into a string variable s and then trying int.Parse(s). The code worked earlier this week and the database has not changed. The only thing that has changed is my environment.
To completely simplify the problem, this line of code throws an exception ("input string was not in the correct format"):
int.Parse("0");
EDIT: Thanks to everyone for helping me resolve this issue! The solution was forcing a reset of my language settings.
A possible explanation:
Basically, the problem was the
sPositiveSign value under
HKEY_CURRENT_USER\Control
Panel\International being set to 0,
which means the positive sign is '0'.
Thus, while parsing the "positive sign
0" is being cut off and then the rest
of the string ("") is parsed as a
number, which doesn't work of course.
This also explains why int.Parse("00")
wasn't a problem. Although you can't
set the positive sign to '0' through
the Control Panel, it's still possible
to do it through the registry, causing
problems. No idea how the computer of
the user in the post ended up with
this wrong setting...
Better yet, what is the output of this on your machine:
Console.WriteLine(System.Globalization.NumberFormatInfo.GetInstance(null).PositiveSign);
I'm willing to bet yours prints out a 0... when mine prints out a + sign.
I suggest checking your Control Panel > Regional and Language Options settings... if they appear normal, try changing them to something else than back to whatever language you're using (I'm assuming English).
I think it's generally not considered a good idea to call Convert.ToInt32 for the value reading out of database, what about the value is null, what about the value cannot be parsed. Do you have any exception handling code here.
Make sure the value is not null.
Check the value can be parsed before call Int32.Parse. Consider Int32.TryParse.
consider use a nullable type like int? in this case.
HTH.
Edit:
#Mike's response made me think that is extremely odd behavior and a simple google search yielded this result: int.Parse weird behavior
An empty string would also cause this issue.
You could check for dbnull before parsing, also it is good to validate parsed data.
You could use a default value and TryParse..
int i = -1;
if(!int.TryParse(dr["MyColumn"] as string, out i))
//Uh Oh!
Edit:
I posted this as a comment in #Chris' answer, but if the sql datatype is int then why not just use the GetInt32 method on the DataReater instead of retrieving it as a string and manual parsing it out?
Are you sure it's "0" and not "null"? What exception do you get?
EDIT:
Just out of curiosity, if it is really faulting on int.Parse("0"), can you try int.Parse("0", CultureInfo.InvariantCulture);?
Otherwise, post your query. Any joins?
you should check dr["FieldName"] != DBNull.Value and you should use TryParse if it passes the DBNull test...
if ( dr["FieldName"] != DBNull.Value )
{
int val = 0;
if ( int.TryParse( dr["FieldName"], out val ) )
{
i = val;
}
else
{
i = 0; // or some default value
}
}
I have seen this issue crop up with .NET Double class, parsing from string "0" as well.
Here's the really wacky part: you can get past the issue by using a different user account to run the program, and sometimes if you destroy and re-create the current user account on the machine, it will run fine.
I have yet to track this down, but you might get past it this way at least.
This is way out of left field, but check your localization settings. I had a number of "input string was not in a correct format" when I moved a web site to a Canadian server. The problem was in a DateTime.Parse method, and was fixed by setting the culture to "en-US".
Yes, your situation is different — but hey, you never know.
are you checking for null ?
if(!dr.IsNull("FieldName")){
int i = Convert.ToInt32(dr["FieldName"]))
}

Categories

Resources