|
I want to change text color on a single line of text with DrawString().
Ex. <red>The <blue>qui<red>ck, b<blue>rown f<red>ox easily jumps over the lazy dog.
I'm trying to use Graphics.MeasureCharacterRanges(), this method gets the ranges
of a number of characters. All fine. Then I can use a TextureBrush with a colored
image to change the text color. The problem is that I can't use this method when rendering
Italic style text. The color rectangles don't compensate for italics text.
If anyone have any tips or a better method to do this, I will be very grathful.
Many thanks, Gywox
<br />
public void DrawTextColor(PaintEventArgs e)<br />
{<br />
Graphics graphics = e.Graphics;<br />
Rectangle layoutRect = new Rectangle(20, 20, 400, 100);<br />
Font tnrFont = new Font("Times New Roman", 24, FontStyle.Italic);<br />
StringFormat strFormat = new StringFormat();<br />
CharacterRange[] charRanges = {<br />
new CharacterRange(3, 4), <br />
new CharacterRange(12, 6) };<br />
Region[] charRegions = new Region[charRanges.Length];<br />
string str = "The quick, brown fox easily jumps over the lazy dog.";<br />
strFormat.SetMeasurableCharacterRanges(charRanges);<br />
<br />
Image image = new Bitmap(layoutRect.Width, layoutRect.Height);<br />
Graphics graphicsImage = Graphics.FromImage(image);<br />
graphicsImage.FillRectangle(Brushes.Red, 0, 0, image.Width, image.Height);<br />
<br />
charRegions = graphics.MeasureCharacterRanges(str, tnrFont, layoutRect, strFormat);<br />
for (int index = 0; index < charRegions.Length; index++)<br />
{<br />
RectangleF boundsRect = charRegions[index].GetBounds(graphics);<br />
graphicsImage.FillRectangle(Brushes.Blue, boundsRect);<br />
}<br />
TextureBrush textureBrush = new TextureBrush(image);<br />
graphics.DrawString(str, tnrFont, textureBrush, layoutRect, strFormat);<br />
}<br />
Gywox
|
|
|
|
|
Is there a way to test if a file is locked, without opening a FileStream? I find it particularly annoying that when you try to open a file that's locked, an exception is thrown. That's a really dumb use for an exception, but equally dumb is that there is no "test" function, as far as I know.
Interestingly, .NET 2.0 fixes a lot of this by providing "can succeed" type of methods, which is much faster than throwing an exception.
And yes, I know that a "can succeed" on a file lock might return true but then the subsequent Open call will fail because the file got suddenly locked.
Marc
MyXaml
Advanced Unit Testing
|
|
|
|
|
Would you rather have return codes like all the Win32 APIs? An exception is what should be thrown from the constructor. Would you rather it return null and not know why it returned null?
This is consistent with how the native APIs work, as I'm sure you know. When you call CreateFile you will get a return code that states the file is locked.
BTW, I don't see any such "can succeed"-type methods in the latest bits for 2.0 for the file-related APIs. Where did you see such information?
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles] [My Blog]
|
|
|
|
|
Heath Stewart wrote:
When you call CreateFile you will get a return code that states the file is locked.
There is no CreateFile method in the .NET FileStream implementation. The API call is embedded in the constructor, it would seem. I would much rather have a method that I can call to test whether the file is locked.
Personally, I've never liked exceptions, except (haha) that they are a useful way of cleaning up the stack. They're innapropriately and inconsistently applied, and often abused.
Heath Stewart wrote:
I don't see any such "can succeed"-type methods in the latest bits for 2.0 for the file-related APIs
Sorry, I meant in general that there's an effort to do this, not that it is specifically done with file-related API's.
Marc
MyXaml
Advanced Unit Testing
|
|
|
|
|
Marc Clifton wrote:
There is no CreateFile method in the .NET FileStream implementation.
Yes, this I know. But if you look at the context, I was talking about native APIs, so I was talking about the native CreateFile API.
Exceptions can be abused, but I think the BCL has a pretty tight reign on them. I see abuses mostly in third-party code (the "less commercial" kind), or just a complete absence of throwing - and especially catching - them.
I personally like them (and other exception mechanisms, like SEH) better than return codes. You don't have to add different conditions with different localized texts (unless you're defining your own exceptions or using your own text, for that matter). The code impact is minimal, but I realize they do cause a slight performance drain to throw, as opposed to just returning an error code. I guess it's really just a matter of opinion, though.
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles] [My Blog]
|
|
|
|
|
I hate to (cough) agree with Marc, but he's right. There no way an exception should be thrown when you can anticipate the failure of a method call beforehand. Exceptions are better thrown when a caller passes a NULL pointer or some other incorrect parameter value to a method when he shouldn't have; that's something you don't expect; that's something you don't know how to deal with; that's something you don't have an error value for; that's when you throw an exception.
Exceptions are for non-recoverable program failures. Proper error-handling is anticipating that a file you're trying to open may not exist; that should not be the cause of an exception.
Seems to me if the framework is going to provide file locking, it needs to provide a test method that does more than just test to see if the file is locked; it should be able to test, lock the file and open it all in one call, because between the return of the test and any attempt to open the file, someone else may beat you to the it, causing you to get the very exception you're trying to avoid by calling the test.
Marc's (cough) correct, as Microsoft has a bad design and implementation, and should fix the problem.
Also, there is no difference in all of the possible errors you can from win32 and the abundance of exceptions you can get from .NET. Exceptions as used today are little more than typed "goto" statements masquerading as objects, deluding people into believing they have OO error management.
When you force a developer to accept exceptions, you're telling him his program is going to run slower so all of the junior programmers using the language can write code that doesn't do proper failure testing, or instead put error-handling code in an else-statement that appears nowhere near the if-statement that tested the condition that failed. A good portion of exception code and logic entanglements (got that word from Marc) can be corrected by correcting the use of if-statements. Namely, don't handle errors in an else clause.
|
|
|
|
|
I'm writing a winforms app in C# that uses XMLHttp to download jpg's from the web. I previously used WebRequest, but decided to switch to XMLHttp because it utilizees IE's browser cache.
However, I can't figure out how to convert the response from XMLHttp into a bitmap. I've tried loading the response into a byte array, converting that to a memory stream, and then using the stream to create the bitmap, but no luck.
Can anoyone give me a pointer on doing this?
Better yet, does anyone know of a .NET framework method that will use the IE cache for http transactions? I know I can build my own using the Cache object, but really don't want to have to do that.
|
|
|
|
|
Does the response actually contain bitmap data, like for a GIF, JPG, PNG, etc. (or perhaps another image that would just be downloaded as binary data instead of being displayed in a page)? Your subject is misleading, which is why I ask.
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles] [My Blog]
|
|
|
|
|
Hi gurus,
I would like to know how to access to the "enable" property of all controls within a form using the foreach loop?
I wish to disable all controls during an operation and enable them once the operation is complete.
Thanks.
Best regards
There is no spoon.
|
|
|
|
|
foreach (Control c in form.Controls)
c.Enabled = false;
Any remotely useful information on my blog will be removed immediately. There are 10 kinds of people in the world. Those who have heard of the ubiquitous, overused, worn-out-like-an-old-shoe binary "joke" and those who haven't.
Judah Himango
|
|
|
|
|
thanks
There is no spoon.
|
|
|
|
|
That'd only work if your controls are nested only 1 level deep. To enable all controls in all containers contained with your container, you'll need to use recursion - not enumeration:
public void EnableAll(bool enabled)
{
this.Enabled = enabled;
EnableAllRecursively(this.Controls, enabled);
}
void EnableAllRecursively(Control.ControlCollection controls, bool enabled)
{
if (controls != null)
{
foreach (Control c in controls)
{
c.Enabled = enabled;
EnableAllRecursively(c.Controls, enabled);
}
}
}
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles] [My Blog]
|
|
|
|
|
Hi,
Thanks to all.
Both techniques work.
In my case Judah's simple loop was the solution I've finally found.
But It is true that the simple loop work only at 1 level.
for nested windows, the recursive version is better...
Thanks to all again
There is no spoon.
|
|
|
|
|
Making such generalized assumptions is not a good practice. The recursive method would be best to implement now in case someday you add a composite control - like a UserControl - to your form. I merely adds an extra 1 or 2 calls to the call stack depending on the state, but still enumerates your first level controls as did the first example.
an even better approach and recursive in nature is to extend a control class and override Enable to also have it disable its children (some controls do this inherently, like the ComboBox ). Then when its children are disabled they disable their children. Now your code isn't responsible for its children and you have a better OO design.
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles] [My Blog]
|
|
|
|
|
Setting the .Enabled property on a control automatically sets the enabled property on all child controls, no?
Say you have 2 panels, and each panel has a button. Disabling the 2 panels will also disable the nested buttons.
Actually, perhaps a better solution would be to simply set the .Enabled property of the form itself, which should also disable any nested controls. Even if you explicitly turn on the Enabled property of a nested control, it will still be disabled if its parent is disabled.
Any remotely useful information on my blog will be removed immediately. There are 10 kinds of people in the world. Those who have heard of the ubiquitous, overused, worn-out-like-an-old-shoe binary "joke" and those who haven't.
Judah Himango
|
|
|
|
|
Typically, yes. It depends on the control.
This posting is provided "AS IS" with no warranties, and confers no rights.
Software Design Engineer
Developer Division Sustained Engineering
Microsoft
[My Articles] [My Blog]
|
|
|
|
|
I don't know if you're talking about a windows app or a web app, but here goes:
Assuming all the controls in question can be enabled or disabled, then you'll have to recurse through the collection of controls from the top (form) level (since controls can contain other controls), so for each control found, you'll have to check its Controls collection.
Whenever you find a control, you'll have to make sure it can be enabled or disabled (meaning you'll have to cast it to its original type or a base type) before setting the enabled/disabled flag.
Please let me know if this isn't detailed enough - I can try to make some sample code, but I'm short on time right now.
The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’
|
|
|
|
|
I'm having an issue with C# string literals. I'm trying to include double quotes in the string for a sql text. I've followed all the advice as to use either the backslash or "double double" quotes, but when I check the resulting output in the command window during debug, I get the backslahes showing up in the string.
code:
(backslash)
string s ="select ld_part, ld_lot, ld__dte01, ld_ref, ld_qty_oh, pt_um, (ld_qty_oh / (ld__dec01 * .012)) when pt_um = \"MS\" from ld_det, pt_mstr where ld_part like \"" + spec + "\" and pt_part = ld_part and ld__Dec01 > 0 and ld_ref= \"\" order by ld__dec01, ld__dte01";
(@ sign and double doubles)
string s = @"select ld_part, ld_lot, ld__dte01, ld_ref, ld_qty_oh, pt_um, (ld_qty_oh / (ld__dec01 * .012)) when pt_um = ""MS"" from ld_det, pt_mstr where ld_part like """ +spec+ @""" and pt_part = ld_part and ld__Dec01 > 0 and ld_ref= """" order by ld__dec01, ld__dte01";
output in command window(either way):
?sql
"select ld_part, ld_lot, ld__dte01, ld_ref, ld_qty_oh, pt_um, (ld_qty_oh / (ld__dec01 * .012)) when pt_um = \"MS\" from ld_det, pt_mstr where ld_part like \"12406%\" and pt_part = ld_part and ld__Dec01 > 0 and ld_ref= \"\" order by ld__dec01, ld__dte01"
desired result:
"select ld_part, ld_lot, ld__dte01, ld_ref, ld_qty_oh, pt_um, (ld_qty_oh / (ld__dec01 * .012)) when pt_um = "MS" from ld_det, pt_mstr where ld_part like "12406%" and pt_part = ld_part and ld__Dec01 > 0 and ld_ref= "" order by ld__dec01, ld__dte01"
Any ideas?
thanks!
Bill Polewchak
Technical Design Lead
Software Development/Architecture
Avery Dennison Corp.
|
|
|
|
|
Both of your examples will produce the same string. The debug window shows the backslashes because it is intended to display "special" characters in that way. When the string is sent to the database, the characters will be expressed as intended, not parsed for display. I don't know what kind of database you're using, but what you have should work in Access.
You might consider sidestepping the whole issue and using single quotes - I think they'll work in Access, and they're required by most other DB platforms instead of double quotes.
One other note: You might want to also consider using parameterized queries instead of putting everything into a single string. I don't know where the value for "spec" comes from, but if it is in any way visible to users, you're opening yourself to SQL injection attack. Also, parameterized queries can often be cached by the DB platform, improving performance.
Hope this helps.
The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’
|
|
|
|
|
Thanks for promptly confirming my hopes! I was wondering whether or not this is a display issue in the command window.
Since this is being used in an oledb (ODBC.NET) object query to a Progress database in our ERP system, I needed to use the double quotes. The resident application db is SQL Server 2000, so in that case, I could have used single quotes, or as I'm more used to doing, using a SQLOLEDB command object to call a parameterized sp!!!
I actually had to do a bit of research to use this old school text method
Thanks again.
cheers,
Bill Polewchak
Team Leader
Software Development/Architecture
Avery Dennison Corp.
|
|
|
|
|
Hello,
I have a database application in my connection string l have the following.
OleDbConnection cnnTeacher = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Library\LibrarySystem.mdb;Persist Security Info=False");
But if want to install this program on another machine l don't want to have to change every connection string. Is there an easy way to do this.
The database is in the same folder that the solution is in.
Thanks in advance,
Steve
|
|
|
|
|
You could create a config (app.config or web.config depending on your project type) file for your application and expose the connection information there as separate variables (e.g. Provider, Data Source, Persist Security Info etc.) See the System.Configuration namespace for information about accessing the contents of config files (or check out the CMAB [Configuration Management Application Block] provided by MS).
This approach is favorable to hard coding the connection information for a number of reasons:
1. You, the developer, are free to change your database platform easily in your development environment.
2. Users of your application can place their datastore where they choose.
3. Changes may be made at any time, and will take effect immediately, and without requiring a recompile.
4. You can encrypt the authentication info in a config file if necessary.
Note: You may also want to include parameters for accessing secured Access databases. Even if you don't lock down the DB currently, you may want to in the future.
Alternate choices to using a config file include using the registry, or a text file.
The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’
|
|
|
|
|
Hello,
I managed to find a solution that worked. I placed the database where the exe file is, and used the Application.StartupPath to get the full path to where the database is.
Is that a good way to solve this problem when you create an installer, to be installed on another machines?
OleDbConnection cnnLogin = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + Application.StartupPath + @"\LibrarySystem.mdb;Persist Security Info=False");
Many thanks in advance,
Steve
|
|
|
|
|
Hi,
I have a user control that includes two other controls, one is a Panel and the other a TextBox (or actually, a user control inherited from a TextBox). The Panel can be used for mouse input (the position of a mouseclick and so on) and the TextBox is there for numerical input. What I want to achieve is that the user can type in a number in the TextBox without having to explicitly give focus to the TextBox first. Preferably, I'd like the TextBox to be filled without ever recieving the focus. I've been able to redirect the key input through the OnKeyDown and OnKeyUp of the user control to those of the TextBox, but it doesn't seem to get processed when the TextBox doesn't have the focus. What I'm desperately trying to prevent is having to catch and interpret every key high-up, for instance in ProcessCmdKey, and then set the text in the TextBox myself. What you're doing then is essentially rebuilding the functionality of a TextBox, which doesn't seem like a good idea.
So I though a good compromise would be to let the user control 'listen' for any key input and take that as a sign that the user wants to use the TextBox. Upon the first encountered key I give the focus to the TextBox and redirect all key input to it. Unfortunately, when the very first key reaches the TextBox, it DOES have the focus but the key still isn't shown. Although the Focused-property of the TextBox is true, somehow it doesn't seem to realise this yet deep down. Calling the TextBox' OnKeyDown twice doesn't help. Only the second key I press gets displayed.
Does anyone know why this occurs or how to circumvent it? Or perhaps someone has an entirely different approach to achieve the effect I'm aiming for, basically a TextBox that can take raw keyboard input but that doesn't need focus.
Thanks.
|
|
|
|
|
I'm a newbie. So please be patient. I'm working on a C# app in compact framework for a PDA. It connects to a device and extracts and updates data. I need to double check with the user before I continue with the update. I would normally use a MessageBox with an OkCancelButton. However, the compact framework doesn't support but one overload: MessageBox(string). I need to send confirmation (bool) back to the form and act accordingly with the update. Could someone please head me in the right direction.
Thanks in advance for any and all help.
|
|
|
|
|