I have a problem with a combo box, I can't display the data inside the combo, I have to do right click before a left click to show my data, but with a just a left click its not possible.
The below image show the first case(when I do a left click)
.
The below image show the second case(when I do a right click before the left click)
Thanks for help
/**
* Configure the renderer appropriately with the status of the
* Drawing object.
*/
public Component getListCellRendererComponent( JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus ) {
Component theResult = super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus );
System.out.println("theResult : "+theResult.toString());
System.out.println("déb methode getLi class AWICombo => value "+value+" ,index "+index+" ,isSelected "+isSelected+",celhasFocus "+cellHasFocus);
// display crash in combo box with jdk 1.3 : setOpaque(true) solves the problem.
//( (JComponent) theResult ).setOpaque( true );
//setOpaque( true );
if ( index == -1 ) {
System.out.println("In if index == -1");
return theResult;
}
try {
System.out.println("In try bloc 1");
boolean notEmpty = false;
AWCState theObjectToDisplay = null;
try {
System.out.println("In try bloc 2");
System.out.println("index " +index);
System.out.println("theModel call :" +theModel.toString());
theObjectToDisplay = (AWCState) theModel.theComboValues.elementAt( index );
System.out.println("theObjectToDisplay => "+theObjectToDisplay.toString());
System.out.println("dans conbobox "+index);
} catch ( java.lang.ArrayIndexOutOfBoundsException aioobe ) {
aioobe.printStackTrace();
}
// test if the first square of the conbo box is empty for doen't set the tool tips
if ( theObjectToDisplay != null ) {
System.out.println("In if 1");
if ( theObjectToDisplay.toString() != null ) {
System.out.println("In if 2");
if ( value.toString().compareTo( theObjectToDisplay.toString() ) != 0 ) {
System.out.println("In if 3");
if ( value.toString().compareTo( "" ) != 0 ) {
System.out.println("In if 4");
theObjectToDisplay = (AWCState) theModel.theComboValues.elementAt( index - 1 );
notEmpty = true;
}
} else {
System.out.println("In else 1");
notEmpty = true;
}
}
} else {
System.out.println("In else 2");
theObjectToDisplay = (AWCState) theModel.theComboValues.elementAt( index - 1 );
notEmpty = true;
}
if ( isSelected ) {
System.out.println("In if isSelected "+list.getSelectionBackground());
System.out.println("In if isSelected "+list.getSelectionForeground());
setBackground( list.getSelectionBackground() );
setForeground( list.getSelectionForeground() );
setToolTip( list, notEmpty, theObjectToDisplay, value );
} else {
setBackground( list.getBackground() );
setForeground( list.getForeground() );
}
setFont( list.getFont() );
if ( value == null ) {
System.out.println("In if value == null");
setText("");
}
else {
setText(value.toString());
}
// object is not obsolete
if ( theObjectToDisplay == null || theObjectToDisplay.getStatus().equals( AWCConstants.OFFICIAL ) ) {
System.out.println("object is not obsolete theObjectToDisplay=>"+theObjectToDisplay.toString());
return theResult;
}
// object is obsolete
if ( index == 1 ) {
return theResult;
}
if ( !isSelected ) {
theResult.setBackground( Color.red );
} else {
theResult.setBackground( new Color( 155, 100, 155 ) );
}
}
catch ( NullPointerException npe ) {
npe.printStackTrace();
}
catch ( java.lang.ArrayIndexOutOfBoundsException aioobe ) {
aioobe.printStackTrace();
}
System.out.println("end of function");
return theResult;
}
Related
I have been trying too parse 2 parameter using for loop but it only loop once and locates one parameter. This is my code.
By providing rectangle 70,80 command in the form, I am trying to draw shapes but while passing through check variable for loop works only once. It does not increments but returns value only after first execution then goes to check number of parameter then rejects with error Array out of bounds.
public String[] ParameterSplit;
public IDictionary<string, int> VariableDictionary = new Dictionary<string, int>();
public IDictionary<string, int> MethodVariableDictionary = new Dictionary<string, int>();
public Boolean AlreadyInArray = false;
public Boolean Value1IsVariable = false;
public Boolean Value2IsVariable = false;
public int value = 0;
public int value1 = 0;
public int value2 = 0;
public CommandParser()
{
}
//This method is used for the validation of commands and parameters which passes thorough
//singleline command and multiline command method
public string[] CommandParsers(string input, int lineCount)
{
string[] text = { };
string[] inputcommand = input.Split(',', ' ');
if (inputcommand[0].ToUpper() == "MOVETO")
{
if(inputcommand.Length < 4)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
}
else
{
if (inputcommand[0].ToUpper() == "DRAWTO")
{
if (inputcommand.Length == 3)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
else
{
MessageBox.Show($"ERROR: Provide correct parameter for moveto in line no {lineCount}");
string[] strings = { "moveto,100,100" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "RECTANGLE")
{
ParameterSplit = inputcommand[1].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
CheckForVariable();
if (ParameterSplit.Length == 2)
{
}
else
{
Convert.ToInt32(ParameterSplit[0]);
Convert.ToInt32(ParameterSplit[1]);
text = ParameterSplit;
}
}
else if (inputcommand[0].ToUpper() == "CIRCLE")
{
if (inputcommand.Length == 2)
{
Convert.ToInt32(inputcommand[1]);
text = inputcommand;
}
else
{
MessageBox.Show("ERROR: Provide correct parameter for circle in line no " + lineCount );
string[] strings = { "circle,20" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "TRIANGLE")
{
if (inputcommand.Length == 3)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
else
{
MessageBox.Show("ERROR: Provide correct parameter for triangle in line no "+ lineCount);
string[] strings = { "triangle,20,60" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "PEN")
{
Pen = true;
string[] validateinput = { "pen", inputcommand[1] };
text = validateinput;
switch (inputcommand[1])
{
case "red":
color = Color.Red;
break;
case "blue":
color = Color.Blue;
break;
case "yellow":
color = Color.Yellow;
break;
case "green":
color = Color.Green;
break;
case "violet":
color = Color.Violet;
break;
}
}
else if (inputcommand[0].ToUpper() == "FILL")
{
string[] validateinput = { "fill", inputcommand[1] };
text = validateinput;
switch (inputcommand[1])
{
case "on":
fill = true;
break;
case "off":
fill = false;
break;
}
}
else if (inputcommand.Length > 2)
{
text = inputcommand;
//checks if the middle element is a "="
if(inputcommand[1].ToUpper() == "=")
{
//check if the variable is already stored or not
//StoreVarialable();
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if (variable.Key.Equals(inputcommand[0]))
{
AlreadyInArray = true;
}
}
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if(variable.Key.Equals(inputcommand[2]))
{
value1 = variable.Value;
Value1IsVariable = true;
}
}
if(inputcommand.Length.Equals(5))
{
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if (variable.Key.Equals(inputcommand[4]))
{
value2 = variable.Value;
Value2IsVariable = true;
}
}
if (AlreadyInArray)
{
VariableDictionary.Remove(inputcommand[0]);
}
}
try
{
if (Value1IsVariable.Equals(false))
{
value1 = Convert.ToInt32(inputcommand[2]);
}
if (Value2IsVariable.Equals(false))
{
if (inputcommand.Length.Equals(5))
{
value2 = Convert.ToInt32(inputcommand[4]);
}
}
if (inputcommand.Length > 3)
{
if (inputcommand[3].Equals("+"))
{
value = value1 + value2;
}
else if (inputcommand[3].Equals("-"))
{
value = value1 - value2;
}
else
{
//InvalidOperator();
}
}
else
{
try
{
value = int.Parse(inputcommand[2]);
}
catch (FormatException ex)
{
//If it is not an integer throw an error
//ValueIsIncorrect();
}
}
//Adds the variable with the inputted value if it is an integer
// VariableDictionary.Add(inputcommand[0], value);
}
catch (FormatException ex)
{
//If it is not an integer throw an error
//ValueIsIncorrect();
//return;
}
}
else
{
}
}
else
{
string[] validateinput = { "error" };
text = validateinput;
}
//end of condition
}
return text;
}
public void CheckForVariable()
{
//Loops through all the parameters
for (int i = 0; i<ParameterSplit.Length ; i++)
{
int index = i;
try
{
//Checks if the parameter is an int
int test = int.Parse(ParameterSplit[index]);
}
catch
{
Boolean foundVariable = false;
foreach (KeyValuePair<string, int> variable in MethodVariableDictionary)
{
if (variable.Key.Equals(ParameterSplit[index]))
{
//if it is then assign the parameter the integer value of the variable
ParameterSplit[index] = variable.Value.ToString();
//ErrorList = ErrorList + variable.Key + ParameterSplit[i] + Environment.NewLine; ;
foundVariable = true;
}
}
if (foundVariable == false)
{
//if it is not then loop through the VariableDictionary to check if the parameter is a variable name
foreach (KeyValuePair<string, int> variable in VariableDictionary)
{
if (variable.Key.Equals(ParameterSplit[i]))
{
//if it is then assign the parameter the integer value of the variable
ParameterSplit[i] = variable.Value.ToString();
}
}
}
}
}
}
//This method is used to get the color from pen by returning its values
internal Color getColor()
{
return color;
}
}
I tried this where I have to check 2 parameter using for loop inside CheckForVariable method
I am downloading images form URL and saving them in pictures directory in folder name unsplash. Now if a user has already downloaded an image I want to show an alert dialog that picture has already been downloaded and if the user wants to download it again. Please help me through it how can I do that.
downloadBtn.setOnClickListener {
if (ContextCompat.checkSelfPermission(
baseContext,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
== PackageManager.PERMISSION_GRANTED
) {
startDownloading(list,position)
} else {
requestDownloadPermission()
}
}
private fun requestDownloadPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
) {
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Permission Required")
dialog.setMessage("Permission Required for downloading this picture." +
"Please go to settings for accessing permission")
dialog.setPositiveButton("Go to setting") { _: DialogInterface, _: Int ->
val openURL = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
openURL.data = Uri.fromParts("package", packageName, null)
startActivity(openURL)
}
dialog.setNegativeButton("cancel") { _: DialogInterface, _: Int -> }
dialog.show()
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
STORAGE_PERMISSION_CODE
)
}
}
private fun startDownloading(list: ArrayList<ImageModel>, position: Int) {
Toast.makeText(this, "Downloading", Toast.LENGTH_SHORT).show()
val downloadList = list[position].urls.raw
val request = DownloadManager.Request(Uri.parse(downloadList))
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_PICTURES,
"/unsplash/${list[position].id}.jpg"
)
.setTitle("Unsplash Images").setAllowedOverMetered(true)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
val manager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
myId = manager.enqueue(request)
var br = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (id == myId) {
Toast.makeText(baseContext, "Downloaded Successfully", Toast.LENGTH_SHORT)
.show()
}
}
}
registerReceiver(br, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
val list = intent.getStringArrayListExtra("FULLIMAGELIST") as ArrayList<ImageModel>
val position = intent.getIntExtra("POSITION", 0)
startDownloading(list,position)
}
} else {
Toast.makeText(baseContext, "Permission Denied", Toast.LENGTH_SHORT).show()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
I have a RSSService with an item like the one show below
<item>
<title>Accessori per la cura della persona</title>
<link>http://www.myurl.it/accessori-per-la-cura-della-persona/</link>
<comments>http://www.myurl.it/accessori-per-la-cura-della-persona/#comments</comments>
<pubDate>Tue, 24 Oct 2017 09:29:44 +0000</pubDate>
<dc:creator><![CDATA[Farmacia Rizzo Davide]]></dc:creator>
<category><![CDATA[News]]></category>
<category><![CDATA[Offerte]]></category>
<category><![CDATA[Callifugo]]></category>
<category><![CDATA[Raspa piedi]]></category>
<category><![CDATA[Spazzola ceramica]]></category>
<category><![CDATA[Spazzola piatta]]></category>
<category><![CDATA[Spazzola tonda]]></category>
<category><![CDATA[Spazzole capelli]]></category>
<guid isPermaLink="false">http://www.myurl.it/?p=3982</guid>
<description>.....
To read all the content I use this:
List<Map> records;
...
records = rss.getResults();
...
for (Map m : records) {
Button b = new Button((String)m.get("title"));
if(((String)m.get("category")).equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
} else {
b.setIcon(iconNews);
}
b.addActionListener((l)->{
Boolean can = Display.getInstance().canExecute((String)m.get("link"));
if(can != null && can) {
Display.getInstance().execute((String)m.get("link"));
} else {
ToastBar.Status status = ToastBar.getInstance().createStatus();
status.setMessage("Non riesco a connettermi");
status.setExpires(3000);
status.show();
}
});
recordsContainer.addComponent(b);
}
When I read the key "category" I always get the last entry (in this item "Spazzole capelli").
There is a way to read a key like an array? Something like that:
String[] mc = (String[]) m.get("category");
Thank's in advance for any help.
Davide.
This looks like a missing feature in RSSService that expects to find only one category entry and so it parses it into a hash map which effectively allows only one such entry.
I would suggest implementing your own RSS reading and go to the XML directly to get the full power of the protocol. You can use the existing class as a reference on how to do the RSS/ATOM parsing.
This is my idea
protected void textElement(String text) {
if(lastTag != null && current != null) {
// make "ATOM" seem like RSS
if("summary".equals(lastTag)) {
current.put("details", text);
} else {
if("content".equals(lastTag)) {
current.put("description", text);
} else {
if(current.get(lastTag) != null){
try {
List list = (List) current.get(lastTag);
list.add(text);
current.put(lastTag, list);
} catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
List list = new ArrayList();
list.add((String)current.get(lastTag));
list.add(text);
current.put(lastTag, list);
}
} else {
current.put(lastTag, text);
}
}
}
}
}
Used in my Form like this:
for (Map m : records) {
Button b = new Button((String)m.get("title"));
try{
String category = (String)m.get("category");
if(category.equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
} else {
b.setIcon(iconNews);
}
} catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
b.setIcon(iconNews);
List list = (List) m.get("category");
for(int i=0; i < list.size(); i++){
if(((String)list.get(i)).equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
}
}
}
b.addActionListener((l)->{
Boolean can = Display.getInstance().canExecute((String)m.get("link"));
if(can != null && can) {
Display.getInstance().execute((String)m.get("link"));
} else {
ToastBar.Status status = ToastBar.getInstance().createStatus();
status.setMessage("Non riesco a connettermi");
status.setExpires(3000);
status.show();
}
});
recordsContainer.addComponent(b);
}
This question is regarding Rasdial and pbk file.
I am updating the pbk file using "rassetentryproperties" and dialling through "rasdialdlg".
The below flags decide the parameters of the pbk file inturn responisble for the property of the dial-up connection.
I am presetting the flags as:
RasEntry.dwfOptions = 0x00000000;
RasEntry.dwfOptions2 = 0x00000000;
Trying to do as below to set Flag1 and Flag2.
RasEntry.dwfOptions |= (Set Flag1 | Set Flag2)
However, my pbk file entries are not actually setting, as i set above.
Also, for the same code, Win7 pbk and win xp pbk are different.
Where i am wrong?
Code Sample for the reference:
BOOL Create_Phone_Book ( LPTSTR DeviceName ) {
DWORD regError;
TCHAR DeviceName[100];
if ( _tcscpy ( DeviceName, DeviceName ) != NULL ) {
Slog ( TEXT ("Strcpy Success"), APISUCCESS );
} else {
Slog ( TEXT ("Strcpy Failed To copy deviceName to DeviceName"), NOLASTERROR);
return FALSE;
}
RASENTRY RasEntry;
DWORD cb;
RASDIALPARAMS RasDialParams;
memset((LPTSTR)&RasEntry, 0, sizeof(RASENTRY));
RasEntry.dwSize = sizeof(RASENTRY);
cb = sizeof(RASENTRY);
regError = RasGetEntryProperties (NULL, TEXT (""), &RasEntry, &cb, NULL, NULL);
if ( regError == ERROR_SUCCESS ) {
Slog ( TEXT ("RasGetEntryProperties Success"), APISUCCESS );
} else {
RAS_ErrorHandler ( regError );
return FALSE;
}
RasEntry.dwfOptions = 0x00000000;
RasEntry.dwfOptions2 = 0x00000000;
RasEntry.dwfOptions |= ( RASEO_IpHeaderCompression | RASEO_ModemLights |RASEO_SwCompression |
RASEO_ShowDialingProgress | RASEO_NetworkLogon | RASEO_DisableLcpExtensions );
RasEntry.dwfOptions2 |= ( RASEO2_UseGlobalDeviceSettings | RASEO2_Internet );
if ( _tcscpy ( RasEntry.szDeviceType, RASDT_Modem ) != NULL ) {
Slog ( TEXT ("Strcpy Success"), APISUCCESS );
} else {
Slog ( TEXT ("Strcpy Failed copy RASDT_MODEM to RasEntry.szDeviceType"), NOLASTERROR);
return FALSE;
}
if ( _tcscpy ( RasEntry.szDeviceName, DeviceName ) != NULL ) {
Slog ( TEXT ("Strcpy Success"), APISUCCESS );
} else {
Slog ( TEXT ("Strcpy Failed copy DeviceName to RasEntry.szDeviceName"), NOLASTERROR);
return FALSE;
}
regError = RasSetEntryProperties( NULL , Dial_Up_Name, &RasEntry, sizeof(RasEntry),NULL, 0);
if ( regError == ERROR_SUCCESS ) {
Slog ( TEXT ("RasSetEntryProperties Succeeded"), APISUCCESS);
} else {
RAS_ErrorHandler ( regError );
return FALSE;
}
memset((LPTSTR)&RasDialParams, 0, sizeof(RasDialParams));
RasDialParams.dwSize = sizeof(RASDIALPARAMS);
if ( _tcscpy (RasDialParams.szEntryName, Dial_Up_Name ) != NULL ) {
Slog ( TEXT ("Strcpy Success"), APISUCCESS);
} else {
Slog ( TEXT ("Strcpy Failed Copy Dial_Up_Name to RasDialParams.szEntryName"), NOLASTERROR);
return FALSE;
}
if ( _tcscpy (RasDialParams.szUserName, TEXT ("")) != NULL ) {
Slog ( TEXT ("Strcpy Success"), APISUCCESS);
} else {
Slog ( TEXT ("Strcpy Failed Copy "" to RasDialParams.szUserName"), NOLASTERROR);
return FALSE;
}
if ( _tcscpy (RasDialParams.szPassword, TEXT ("")) != NULL ) {
Slog ( TEXT ("Strcpy Success"), APISUCCESS);
} else {
Slog ( TEXT ("Strcpy Failed Copy "" to RasDialParams.szPassword"), NOLASTERROR);
return FALSE;
}
regError = RasSetEntryDialParams ( NULL, &RasDialParams, FALSE);
if ( regError == ERROR_SUCCESS ) {
Slog ( TEXT ("RasSetEntryDialParams Success"), APISUCCESS );
} else {
RAS_ErrorHandler ( regError );
return FALSE;
}
return TRUE;
}
Updated 1:
Typically, i need to create an Dial-Up connection as i like. Please look at the screen shot attached.
As seen in the snap, i have to set and reset many parameters(Set-Display Progress while connecting, Reset- Prompt for UN and PW).
These two flags use to set and reset whatever we want by "or"ing
RasEntry.dwfOptions
RasEntry.dwfOptions2
So what i do in my code is :
resetting the flag:
RasEntry.dwfOptions = 0x00000000;
RasEntry.dwfOptions2 = 0x00000000;
and to set:
RasEntry.dwfOptions |= ( RASEO_IpHeaderCompression | RASEO_ModemLights
|RASEO_SwCompression | RASEO_ShowDialingProgress |
RASEO_NetworkLogon | RASEO_DisableLcpExtensions );
So, the remaining flags other than the above, will be remained Unset.
Now the problem is, Whatever i am setting in the above steps are not actually setting in the dial-up connection. In another way, some parameters are not set even, if i set in the code.
What should i do to get rid of my problem?
It is problem of using AutoSize for label which are drawn by Tahoma font with option TextRenderingHint.ClearTypeGridFit.
Without ClearTypeGridFit it looks ok, but with - it cropped by parent container (see attached image: on first label ',' is cropped)
I've found it is only with Tahoma font.
Code of customlabel:
class CustomLabel: Label
{
public CustomLabel ()
:base()
{
}
protected override void OnPaint ( PaintEventArgs e )
{
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
base.OnPaint( e );
}
}
Peace of code from designer file:
//
// label1
//
this.label1.AutoSize = true;
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Font = new System.Drawing.Font( "Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ( (byte)( 0 ) ) );
this.label1.Location = new System.Drawing.Point( 54, 95 );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size( 35, 13 );
this.label1.TabIndex = 1;
this.label1.Text = resources.GetString( "label1.Text" );
//
// customLabel1
//
this.customLabel1.AutoSize = true;
this.customLabel1.BackColor = System.Drawing.Color.NavajoWhite;
this.customLabel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.customLabel1.Font = new System.Drawing.Font( "Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ( (byte)( 0 ) ) );
this.customLabel1.ForeColor = System.Drawing.Color.Black;
this.customLabel1.Location = new System.Drawing.Point( 1, 1 );
this.customLabel1.Margin = new System.Windows.Forms.Padding( 0 );
this.customLabel1.Name = "customLabel1";
this.customLabel1.Size = new System.Drawing.Size( 192, 154 );
this.customLabel1.TabIndex = 0;
this.customLabel1.Text = resources.GetString( "customLabel1.Text" );
What I have found just a overridden a GetPreferedSize function:
public override Size GetPreferredSize ( Size theProposedSize )
{
if ( TextRendering == TextRenderingHint.ClearTypeGridFit )
{
Graphics aGraphics = Graphics.FromHwnd( this.Handle );
if ( aGraphics != null )
{
aGraphics.TextRenderingHint = theTextRendering;
Size aResult = TextRenderer.MeasureText( aGraphics, Text, Font, theProposedSize );
//apply control minimum size
aResult.Height = Math.Max( aResult.Height, MinimumSize.Height );
aResult.Width = Math.Max( aResult.Width, MinimumSize.Width );
return aResult;
}
}
return base.GetPreferredSize( theProposedSize );
}
But I can't apply a Maximum size to the result.
Why I need a Maximum size? For example, I want to have a possibility to limit labels by width.
Any ideas?
So, my final solution looks so:
public override Size GetPreferredSize ( Size theProposedSize )
{
if ( SystemInfo.WinVersion == SystemInfo.Version.WindowsXP )
{
if ( theTextRendering == TextRenderingHint.ClearTypeGridFit )
{
Graphics aGraphics = Graphics.FromHwnd( this.Handle );
if ( aGraphics != null )
{
aGraphics.TextRenderingHint = theTextRendering;
Size aResult = TextRenderer.MeasureText( aGraphics, Text, Font, theProposedSize );
//apply padding and margin
aResult.Width += Margin.Horizontal + Padding.Horizontal;
aResult.Height += Margin.Vertical + Padding.Vertical;
//apply control minimum size
aResult.Height = Math.Max( aResult.Height, MinimumSize.Height );
aResult.Width = Math.Max( aResult.Width, MinimumSize.Width );
//adopt maximum width
if ( MaximumSize.Width > 0 )
{
while ( aResult.Width > MaximumSize.Width )
{
aResult.Width -= MaximumSize.Width;
aResult.Height += Font.Height;
if ( aResult.Width < MaximumSize.Width )
{
aResult.Width = MaximumSize.Width;
}
}
}
return aResult;
}
}
}
return base.GetPreferredSize( theProposedSize );
}