50% OFF!!!

Showing posts with label control. Show all posts
Showing posts with label control. Show all posts

Thursday, December 22, 2016

c# | WebBrowser control - programmatically select item on html `select`

Hi There,

As many times, we need to interact with the C# (.Net) Webbrowser Control, 
it is useful to be able to interact and programmatically change the selected item 
on an HTML select control.

I don't know, why it is hard to find this easy solution, but the code is as follow:


HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("select") 
foreach (HtmlElement heItem in col) 
{ 
  if (heItem.GetAttribute("className").Contains("exampleClassName") == true) 
  { 
    heItem.SetAttribute("selectedIndex", "3"); // select value at #3
    break; // incase of needed... 
  } 
}  


And finally, just easy as u code...


If you need change by value and not by index,
I assume you can check the values of the select control (sometimes called: dropdown),
and once you find the correct index of the desired value,
use the code above.



MDB-BLOG :)

Sunday, November 14, 2010

C# | Winforms | Textbox within Button

Here is an example for creating a Button control which contains a Textbox inside it.
This is very usefull when the button functionality is based (only) on the textbox content text, and it is very usefull for the user.

Screenshot (image) example:


The Code:
class ButtonWithTextbox : Button
{
    TextBox _textbox = new TextBox();

    public int TextboxWidth
    {
        get { return _textbox.Width; }
        set { _textbox.Width = value; }
    }
    public Point TextboxLocation
    {
        get { return _textbox.Location; }
        set { _textbox.Location = value; }
    }
    /** And we may add all properties of the Textbox ***/

    public ButtonWithTextbox()
    {
        this.Controls.Add(_textbox);
    }
}

Also work great on the designer... :)

MDB-Blog
http://mdb-blog.blogspot.com

Tuesday, June 22, 2010

lwuit | j2me link control (component)

Here is an implemantation of a LINK component for the LWUIT enviroment under J2ME (Java ME).
This code creates a lwuit link component based on the lwuit button which not have a border and is transparent! also have an appropriate color (blue) and font style (underline).
hope it is helpful:

code example:

Button btn = new Button("LINK1");
//btn.getStyle().setBorder(Border.createEmpty());
btn.getUnselectedStyle().setBorder(Border.createEmpty());
btn.getSelectedStyle().setBorder(Border.createEmpty());

//btn.getStyle().setBgTransparency(100);
btn.getUnselectedStyle().setBgTransparency(100);
btn.getSelectedStyle().setBgTransparency(100);

//btn.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, Font.SIZE_MEDIUM));
btn.getUnselectedStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, Font.SIZE_MEDIUM));
btn.getSelectedStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED | Font.STYLE_BOLD, Font.SIZE_MEDIUM));

//btn.getStyle().setFgColor(0x0000ff);
btn.getUnselectedStyle().setFgColor(0x0000ff);
btn.getSelectedStyle().setFgColor(0x0000ff);



Enjoy!

Tuesday, November 10, 2009

Asp.Net - Make short ids for controls

Here is a code for making your controls names/ids shorten than it is, because asp.net as default make every control name: {parent-id}_{control-id} and it makes html code length larger...


public class BasePage : Page
{
protected override void OnInit(EventArgs p_eventArgs)
{
MakeIdsShorted(this, true);
base.OnInit(p_eventArgs);
}

private int currentId = 0;
private void MakeIdsShorted(Control p_ctrl, bool p_recursive)
{
if (p_ctrl is Login)
{
return; // ignore ASP.Login controls
}
if (string.IsNullOrEmpty(p_ctrl.ID) == false)
{
//this.EnsureID();
p_ctrl.ID = "c" + currentId; // p_ctrl.ID.GetHashCode();
currentId++;
}

if (p_recursive == true)
{
foreach (Control c in p_ctrl.Controls)
{
MakeIdsShorted(c, true);
}
}
}
}



Make sure your created page is inherits from BasePage...
:)

Monday, July 6, 2009

Javascript html date control (validation)


Here is a sample code for an html input date control include DATE validation!
I searched a lot for such method for integration with PHP page but was little difficult.

Here is the HTML CODE:
<input id="inputDate1" name="Field1" value="21/07/2006" type="text" onblur="validateDate(this, '/')" maxlength="10">

<button onclick="setTodayDate(this.previousSibling, '/')">today</button>



Here is the JAVASCRIPT CODE:
function validateDate(p_inputObj, delim)
{
var text = p_inputObj.value;
var errorMsgs = "Following error(s) :\n";
var isDateCorrect = true;

var delim1 = text.indexOf(delim);
var delim2 = text.indexOf(delim, delim1+1);
if (delim2 <= delim1)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Must be in format of dd/mm/yyyy like (21/09/2008)\n";
}
else
{
var day = parseInt(text.substring(0, delim1), 10);
var splitter1 = text.substring(delim1, delim1+1);
var month = parseInt(text.substring(delim1+1, delim2), 10);
var splitter2 = text.substring(delim2, delim2+1);
var year = parseInt(text.substring(delim2+1), 10);

if (isNaN(day) || isNaN(month) || isNaN(year))
{
isDateCorrect = false;
if (isNaN(day)) { errorMsgs = errorMsgs + "- Day not in correct format!\n"; }
if (isNaN(month)) { errorMsgs = errorMsgs + "- Month not in correct format!\n"; }
if (isNaN(year)) { errorMsgs = errorMsgs + "- Year not in correct format!\n"; }
}
else
{
if (day<1)
{
errorMsgs = errorMsgs + "- Day must be between grater than 0\n";
isDateCorrect = false;
}

if (month>12 || month<1)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Month must be between 01 to 12\n";
}
else
{
if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12 )
{
if (day>31)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 31\n";
isDateCorrect = false;
}
}
else if(month==2)
{
// is leap year
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
if (day>29)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 29\n";
isDateCorrect = false;
}
}
else
{
if (day>28)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 28\n";
isDateCorrect = false;
}
}
}
else
{
if (day>30)
{
errorMsgs = errorMsgs + "- Day must be between 1 to 30\n";
isDateCorrect = false;
}
}
}

if (year<2000)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Year not valid. must be more than 2000!\n";
}
else if (year>9999)
{
isDateCorrect = false;
errorMsgs = errorMsgs + "- Year must be 4 digits!\n";
}
}
}

if (isDateCorrect == true)
{
var newStr = (day<10 ? '0' : '') + day + delim +
(month<10 ? '0' : '') + month + delim +
year; // +" "+hour+":"+minute+" "+AMPM;
p_inputObj.title = '';
var date = new Date();
date.setFullYear(year, month-1, day);
p_inputObj.dateVal = date;
p_inputObj.value = newStr;
p_inputObj.style.backgroundColor='#FFFFFF';
return true;
}
else
{
//alert(errorMsgs);
errorMsgs = errorMsgs.substring(0, errorMsgs.length-1);
p_inputObj.dateVal = null;
p_inputObj.title = errorMsgs;
p_inputObj.style.backgroundColor='#ffaaaa';
p_inputObj.focus();
return false;
}
}

function setTodayDate(p_inputObj, p_delim)
{
var dtNow = new Date();
var day = dtNow.getDate();
var month = dtNow.getMonth() + 1;
var year = dtNow.getFullYear();
p_inputObj.value = (day<10 ? '0' : '') + day + p_delim +
(month<10 ? '0' : '') + month + p_delim +
year;
}


Date format if dd/MM/yyyy but it can also be MM/dd/yy or yyyy!
Enjoy... :)

Tuesday, June 16, 2009

J2ME | Analog Clock control - custom item



Here is an example for anlogic clock control (extends CustomItem) which may be added to Form class and also in Canvas class.
for Form class just add it as and item,
and for Canvas class and its paint method, provide graphics to AnalogClock's paint method.

Here is Code for the analog clock:


package CustomItems;

import javax.microedition.lcdui.*;
import java.util.Calendar;

public class AnalogClock extends CustomItem implements Runnable
{

private double diam = 0.38;
private double LineLengthSeconds = 0.90;
private double LineLengthMinutes = 0.75;
private double LineLengthHour = 0.50;
private double LineLengthTicks = 0.08;
private double TextPositionRelativeR = 1.22;
//
/***
* Represents control's width
*/
private int Width = 100;
/***
* Represents control's height
*/
private int Height = 100;
/***
* Represents clock's radius
*/
private int _raduis;
/***
* Represents clock's center point - X
*/
private int _circleCenterX;
/***
* Represents clock's center point - Y
*/
private int _circleCenterY;
/***
* Represents clock's current date&time
*/
private Calendar _now;
/***
* Represents the thread which implement the clock's ticks
*/
private Thread _thread = null;
/***
* Represents a flag which describe if the thread is running or not
*/
private boolean _threadIsRunning = false;
//
/***
* Represents the background color of the clock
*/
public int BackColor = 0xffffff;
/***
* Represents the color of the clock (text & lines)
*/
public int ClockColor = 0x000000;
/***
* A flag which represent whether or not display the date inside the clock
*/
public boolean ShowDate = false;
/***
* Represents the font of the text drawn
*/
public Font Font;

/** Creates a new instance of AnalogClock */
public AnalogClock(String p_label, int p_size)
{
super(p_label);
if (p_size <= 0)
{
sizeChanged(Width, Height);
}
else
{
sizeChanged(p_size, p_size);
}
Font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
}

protected int getMinContentWidth()
{
return 10;
}

protected int getMinContentHeight()
{
return 10;
}

protected int getPrefContentWidth(int p_height)
{
return Width;
}

protected int getPrefContentHeight(int p_width)
{
return Height;
}

protected void sizeChanged(int p_w, int p_h)
{
Height = p_h;
Width = p_w;
int size = Math.min(Width, Height);
_raduis = (int) (diam * (double) size);
_circleCenterX = size / 2;
_circleCenterY = size / 2;
_now = Calendar.getInstance();
}

private int pointX(double minute, double radius, int _circleCenterX)
{
double angle = minute * Math.PI / 30.0;
return (int) ((double) _circleCenterX + radius * Math.sin(angle));
}

private int pointY(double minute, double radius, int oy)
{
double angle = minute * Math.PI / 30.0;
return (int) ((double) oy - radius * Math.cos(angle));
}

public void updateTime()
{
_now = Calendar.getInstance();
repaint();
}

public void updateTime(Calendar p_currtime)
{
_now = p_currtime;
repaint();
}

protected void paint(Graphics g, int w, int h)
{
// clear background
g.setColor(BackColor);
g.fillRect(0, 0, Width - 1, Height - 1);
g.setColor(ClockColor);

// draw circle
g.drawArc(_circleCenterX - _raduis, _circleCenterY - _raduis, _raduis * 2, _raduis * 2, 0, 360);

// set text's font
g.setFont(Font);
int textH = Font.getHeight();

// draw date (if allowed)
if (ShowDate == true)
{
String strDate = getDateString(_now, "-");
int strDateWidth = Font.stringWidth(strDate);
g.drawRect(_circleCenterX - strDateWidth / 2, _circleCenterY, strDateWidth, textH);
g.drawString(strDate, _circleCenterX, _circleCenterY, Graphics.TOP | Graphics.HCENTER);
}

// draw ticks & digits
int textW;
for (int hour = 1; hour <= 12; hour++)
{
double angle = hour * 60.0 / 12.0;
g.drawLine(
pointX(angle, _raduis * (1 - LineLengthTicks), _circleCenterX),
pointY(angle, _raduis * (1 - LineLengthTicks), _circleCenterY),
pointX(angle, _raduis, _circleCenterX),
pointY(angle, _raduis, _circleCenterY));

// texts
textW = Font.stringWidth("" + hour);
g.drawString("" + hour,
(int) pointX(angle, _raduis * TextPositionRelativeR, _circleCenterX) - textW / 2,
(int) pointY(angle, _raduis * TextPositionRelativeR, _circleCenterY) - textH / 2,
0);
}

double hour = _now.get(Calendar.HOUR) * 60.0 / 12.0;
double minute = _now.get(Calendar.MINUTE);
double second = _now.get(Calendar.SECOND);

// draw hour line
g.drawLine(_circleCenterX, _circleCenterY,
pointX(hour + (double) minute / 12.0, _raduis * LineLengthHour, _circleCenterX),
pointY(hour + (double) minute / 12.0, _raduis * LineLengthHour, _circleCenterY));

// draw minutes line
g.drawLine(_circleCenterX, _circleCenterY,
pointX(minute + second / 60.0, _raduis * LineLengthMinutes, _circleCenterX),
pointY(minute + second / 60.0, _raduis * LineLengthMinutes, _circleCenterY));

// draw seconds line
g.drawLine(_circleCenterX, _circleCenterY,
pointX((double) second, _raduis * LineLengthSeconds, _circleCenterX),
pointY((double) second, _raduis * LineLengthSeconds, _circleCenterY));
}

public synchronized void startTicking()
{
if (_thread == null)
{
_thread = new Thread(this);

_threadIsRunning = true;
_thread.start();
}
}

public synchronized void stopTicking()
{
if (_thread != null)
{
_threadIsRunning = false;
try
{
_thread.join();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}

public void run()
{
while (_threadIsRunning == true)
{
this.updateTime();

try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}

private String getDateString(Calendar p_calendar, String p_delimiter)
{
int day = p_calendar.get(Calendar.DAY_OF_MONTH);
int month = p_calendar.get(Calendar.MONTH) + 1;
int year = p_calendar.get(Calendar.YEAR);

String strDay = (day < 10) ? "0" + day : String.valueOf(day);
String strMonth = (month < 10) ? "0" + month : String.valueOf(month);
String strYear = String.valueOf(year);

StringBuffer sb = new StringBuffer();
sb.append(strDay);
sb.append(p_delimiter);
sb.append(strMonth);
sb.append(p_delimiter);
sb.append(strYear);

return sb.toString();
}
}


Usage sample:

package Test;

import CustomItems.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class StartMidlet extends MIDlet implements CommandListener
{
public void startApp()
{
Form f = new Form("My Clock Test");
int w = f.getWidth();
int h = f.getHeight();

AnalogClock cl = new AnalogClock(null, (int) (w * 0.8));
cl.setLayout(Item.LAYOUT_2 | Item.LAYOUT_CENTER);
cl.startTicking();
f.append(cl);

Command cmd = new Command("Back", Command.BACK, 0);
f.addCommand(cmd);

cmd = new Command("Next", Command.OK, 1);
f.addCommand(cmd);

f.setCommandListener(this);

Display.getDisplay(this).setCurrent(f);
}

public void pauseApp()
{ }

public void destroyApp(boolean unconditional)
{ }

public void commandAction(Command arg0, Displayable arg1)
{ }
}




The contorl have 2 methods for managing clock timer.
startTicking - for start ticking the timer (this calls repaint...)
stopTicking- for stop the timer



Use it smartly...

Tuesday, September 2, 2008

Compact Framework | Scrolling on control



Scrolling inside a control from the code is very simple.
All you have to do is to give the control the new location (Point: x,y)
and it will scroll to the new point...

My generic method scrolls the item each time by ~66% of its size (2/3)
Note: in my example, the scrolling obect is this!



int changeHeight = this.Height * 2 / 3;
if (p_pressedKey == Keys.Down)
{
this.AutoScrollPosition = new Point(this.AutoScrollPosition.X, -this.AutoScrollPosition.Y + changeHeight);
}
else if (p_pressedKey == Keys.Up)
{
this.AutoScrollPosition = new Point(this.AutoScrollPosition.X, -this.AutoScrollPosition.Y - changeHeight);
}





Monday, August 25, 2008

Picture with transparent label


A picturebox object that supports a label (transparent).
this allow to create a piture button and add text it.
This control tested and working :)

use it with wisdom... or not:
have fun:



public class PictureText : PictureBox, ISupportInitialize
{
#region #region Private Data-Members

private string _textDisplayed = string.Empty;

private Font _textFont = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold);

private Color _textForeColor = Color.Black;

#endregion

public string TextDisplayed
{
get { return _textDisplayed; }
set
{
_textDisplayed = value;
this.Invalidate();
}
}
public Font TextFont
{
get { return _textFont; }
set
{
_textFont = value;
this.Invalidate();
}
}
public Color TextForeColor
{
get { return _textForeColor; }
set
{
_textForeColor = value;
this.Invalidate();
}
}

//protected override void OnPaintBackground(PaintEventArgs e)
//{
// base.OnPaintBackground(e);

// //HorizontalAlignment.
// if (string.IsNullOrEmpty(TextDisplayed) == false)
// {
// e.Graphics.DrawString(this.TextDisplayed, this.TextFont, new SolidBrush(this.TextForeColor), this.Location.X, this.Location.Y);
// }
//}

protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);

if (string.IsNullOrEmpty(TextDisplayed) == false)
{
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;

e.Graphics.DrawString(this.TextDisplayed, this.TextFont, new SolidBrush(this.TextForeColor), this.Width / 2, this.Height / 2, sf);
}
}
}

#region ISupportInitialize Members
public void BeginInit()
{
}
public void EndInit()
{
}
#endregion
}




Tuesday, August 19, 2008

Making control RTL or LTR

As many people asked me for making rtl or ltr controls on the compactframework.
My best solution for this question is:

public const int GWL_EXSTYLE = (-20);
public const int WS_EX_LAYOUTRTL = 0x400000;
public static void SetControlDirection(Control c, bool p_isRTL)
{
int style = GetWindowLong(c.Handle, GWL_EXSTYLE);

// set default to ltr (clear rtl bit)
style &= ~WS_EX_LAYOUTRTL;

if (p_isRTL == true)
{
// rtl
style = WS_EX_LAYOUTRTL;
}

SetWindowLong(c.Handle, GWL_EXSTYLE, style);
c.Invalidate();
}


[DllImport("coredll.dll")]
static extern int GetWindowLong(IntPtr hWnd, int cmd);

[DllImport("coredll.dll")]
static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);





CE OS supported:

I tried on "Windows Mobile 6 Classic" emulator and it worked. (CE OS = 5.2)

On "Windows Mobile 5.0 Pocket PC" emulator, also worked. (CE OS = 5.1)


On "Pocket PC 2003 SE" emulator, it did NOT worked! (CE OS = 4.21)


Free Image Hosting at www.ImageShack.us

Download sample test





I hope it will be helpful for you... :)

Tuesday, August 12, 2008

Auto Sized Label for cf

Auto Sized Label control for the compact framework:

I noticed that there is no solution for an autosized label (auto width & height)

so i build my example for this control:




public class AutoSizeLabel : Label
{
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
ReCalculateSize();
}
}
public override System.Drawing.Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
ReCalculateSize();
}
}
private void ReCalculateSize()
{
using (Control control = new Control())
{
using (Graphics g = control.CreateGraphics())
{
SizeF size = g.MeasureString(base.Text, base.Font);
base.Width = (int)size.Width + 1;
base.Height = (int)size.Height + 1;
}
}
}
}


i hope it will help you...