Label's position is different in xp and 7 - c#

I made small application(winforms) to show the cricket score (the world has just started , yay).
It works fine in xp, but in win 7 the label shows a few pixels down in position as compared to its position in xp, which totally ruins everything. ( i hope that was clear )
here is the exe: [REDACTED]
how it looks in xp; http://imgur.com/emcKG.jpg
how it looks in 7(approx): http://imgur.com/sdqry.jpg
also can someone confirm which .net my app requires ? I think its .net 2.0, since the target framework is set to .Net 2.0 .
Thanks
Edit: won't post the exe next time. sorry!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int numberOfMatches = 0;
int selectedmatch = 0;
string[,] data;
string fileToParse = Path.GetTempPath() + "cricketfile.xml";
int matchToShow = 0;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd,
int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public Form1()
{
InitializeComponent();
int X = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2;
this.Location = new System.Drawing.Point(X, -5);
if (rkApp.GetValue("cricketscore") == null)
{
startWithWindowsToolStripMenuItem.Checked = false ;
}
else
{
startWithWindowsToolStripMenuItem.Checked = true ;
}
this.Region = new Region(new Rectangle(10, 10, 197, 17));
ToolTip tooltip = new ToolTip();
tooltip.SetToolTip(pictureBox1, " right click for settings, left click to move");
tooltip.SetToolTip(label1, " right click for settings, left click to move");
fetchData();
addContextEntries();
chooseIndia();
updateScore();
// MessageBox.Show(data.GetLength(0).ToString());
//foreach (string s in data)
//{
// Console.WriteLine(s);
//}
timer1.Interval = 10 * 1000;
timer1.Enabled = true;
}
public void addContextEntries()
{
// MessageBox.Show("num- " + numberOfMatches);
List<ToolStripMenuItem> Mylist1 = new List<ToolStripMenuItem>();
for (int i = 0; i < numberOfMatches; i++)
{
Mylist1.Add( new ToolStripMenuItem() );
this.contextMenuStrip1.Items.Add(Mylist1[i]);
Mylist1[i].Text = "See Match " + (i + 1) + "'s score";
switch(i)
{
case 0:
Mylist1[i].Click += new System.EventHandler(this.match1);
break;
case 1:
Mylist1[i].Click += new System.EventHandler(this.match2);
break;
case 2:
Mylist1[i].Click += new System.EventHandler(this.match3);
break;
case 3:
Mylist1[i].Click += new System.EventHandler(this.match4);
break;
case 4:
Mylist1[i].Click += new System.EventHandler(this.match5);
break;
}
}
}
public void match1(object sender, EventArgs e)
{
// MessageBox.Show("match 1");
matchToShow = 0;
label1.Text = data[0, 0] + " " + data[0, 1];
}
public void match2(object sender, EventArgs e)
{
// MessageBox.Show("match 2");
matchToShow = 1;
label1.Text = data[1, 0] + " " + data[1, 1];
}
public void match3(object sender, EventArgs e)
{
matchToShow = 2;
label1.Text = data[2, 0] + " " + data[2, 1];
}
public void match4(object sender, EventArgs e)
{
matchToShow = 3;
label1.Text = data[3, 0] + " " + data[3, 1];
}
public void match5(object sender, EventArgs e)
{
matchToShow = 4;
label1.Text = data[4, 0] + " " + data[4, 1];
}
public void chooseIndia()
{
for (int i = 0; i < data.GetLength(0); i++)
{
// MessageBox.Show("i - " + i);
if (data[i, 3].ToLower().Contains("australia"))
{
matchToShow = i;
// MessageBox.Show("i - " + i);
break;
}
}
}
public void updateScore()
{
fetchData();
//foreach (string s in data)
//{
// Console.WriteLine(s);
//}
// MessageBox.Show("matchToShow- " + matchToShow);
label1.Text = data[matchToShow,0] + " " + data[matchToShow ,1];
}
public void fetchData()
{
int matchnumber = -1;
numberOfMatches = 0;
WebClient Client = new WebClient();
try
{
Client.DownloadFile("http://synd.cricbuzz.com/score-gadget/gadget-scores-feed.xml", fileToParse);
}
catch ( WebException we)
{
if (we.ToString().ToLower().Contains("connect to"))
;//MessageBox.Show("unable to connect to server") ;
}
XmlTextReader xmlreader0 = new XmlTextReader(fileToParse);
while (xmlreader0.Read())
{
if (xmlreader0.Name.ToString() == "match" && xmlreader0.NodeType == XmlNodeType.Element)
{
++numberOfMatches;
}
}
data = new string[numberOfMatches, 4];
// numberOfMatches = 0;
// MessageBox.Show("matchnumbers - " + numberOfMatches);
XmlTextReader xmlreader = new XmlTextReader(fileToParse);
while (xmlreader.Read())
{
if (xmlreader.Name.ToString() == "header" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 0] = xmlreader.Value;
// MessageBox.Show(xmlreader.Value);
}
if (xmlreader.Name == "description" && xmlreader.NodeType == XmlNodeType.Element)
{
// MessageBox.Show(xmlreader.Value);
xmlreader.Read();
// MessageBox.Show("matched - " + xmlreader.Value);
data[matchnumber, 1] = xmlreader.Value;
}
if (xmlreader.Name == "url-text" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
// MessageBox.Show(xmlreader.Value);
data[matchnumber, 2] = xmlreader.Value;
}
if (xmlreader.Name == "url-link" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 3] = xmlreader.Value;
}
if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
{
matchnumber++;
}
}
xmlreader.Close();
xmlreader0.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
updateScore();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void switchColrosToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( label1.ForeColor == System.Drawing.Color.Black)
label1.ForeColor = System.Drawing.Color.White ;
else
label1.ForeColor = System.Drawing.Color.Black;
}
private void startWithWindowsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void startWithWindowsToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
{
if (startWithWindowsToolStripMenuItem.Checked == true)
{
rkApp.SetValue("cricketscore", Application.ExecutablePath.ToString());
}
else
{
rkApp.DeleteValue("cricketscore", false);
}
}
private void showFullScorecardToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(data[matchToShow, 3]);
}
private void label1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
//public void findNumberOfMatches()
//{
// if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
// {
// matchnumber++;
// }
//}
}
}
btw how do I get by exe verified , so that normal people can use it without fear ? virustotal.com ?
Edit: oops , I was wrong ,tis not just the label. the picturebox to the left of the label has also been shifted down a few pixels.

It appears, from your screenshots, that the entire box that holds the text shrinks, and there's a blue bar that covers part of the label.
Perhaps it is a resolution issue or dpi issue. also they change color from one OS to the other??
You might need to set the locations and other properties in the code with a static ,hard coded values, rather than letting windows place it from the designer view or using some variable number based on the size of the screen
this is in c#.net should be similar
label1.Left = 10;
label1.Top = 10;

this.Region = new Region(new Rectangle(10, 10, 197, 17));
Delete that. It makes your window too small on a machine with a higher video dots-per-inch setting. Quite common on Win7. A higher DPI makes the fonts taller in pixels. The Form.AutoScaleMode property automatically adjusts for that by making the controls larger to fit that bigger font. Your Region doesn't grow though, cutting off the bottom of the controls. No idea why you use a Region in the first place since its a plain rectangle, I suppose you are looking for FormBorderStyle = None. A form won't allow you to make it too small but you can override that in the OnLoad method. Set the ClientSize large enough to fit the rescaled controls.

This has to do with a difference in the DPI settings on Windows XP and Windows 7.
How to change DPI on Windows 7.
How to change DPI on Windows XP.

Related

Clipboard copies twice

(Short Screen-Cast explaining the problem)
I'm making a Clipboard program, that allows you to see what's in your clipboard.
It looks like this:
It seems to work fine copying on-the-fly.
The problem is that I want to be able to go back to a previous img/txt in clipboard and use it - that's when I use the check-mark button.
It works, the only problem is that it copies it twice into the list of images / listbox I'm using. It also happens when I initialize the listbox/picturebox.
Here's the code:
namespace Clipboard_Wizard
{
public partial class FormMain : Form
{
//register the program in the clipboard viewer chain
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);
private const int WM_DRAWCLIPBOARD = 0x0308; // WM_DRAWCLIPBOARD message
private IntPtr _clipboardViewerNext; // Our variable that will hold the value to identify the next window in the clipboard viewer chain
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
ChangeClipboardChain(this.Handle, _clipboardViewerNext); // Removes our from the chain of clipboard viewers when the form closes.
}
List<Image> img = new List<Image>();
int ImgCount = 0;
int ImgIndex = -1;
Image tmp;
public FormMain()
{
InitializeComponent();
_clipboardViewerNext = SetClipboardViewer(this.Handle); // Adds our form to the chain of clipboard viewers.
//set listbox/picturebox to whatever already on clipboard
if (Clipboard.ContainsImage())
{
tmp = Clipboard.GetImage();
pictureBox1.Image = tmp;
img.Add(tmp);
ImgCount++;
ImgIndex++;
btnSlctImg.Enabled = true;
label3.Text = "Image 1 / 1";
}
else if (Clipboard.ContainsText())
{
listBox1.Items.Add(Clipboard.GetText());
}
}
// clears everything from the form and the clipboard
private void btnClear_Click(object sender, EventArgs e)
{
Clipboard.Clear();
listBox1.Items.Clear();
img.Clear();
pictureBox1.Image = null;
ImgCount = 0;
ImgIndex = -1;
btnSlctImg.Enabled = false;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
/*if (Clipboard.ContainsImage())
{
tmp = Clipboard.GetImage();
pictureBox1.Image = tmp;
img.Add(tmp);
ImgCount++;
ImgIndex = ImgCount - 1;
}
else if (Clipboard.ContainsText())
{
listBox1.Items.Add(Clipboard.GetText());
listBox1.TopIndex = listBox1.Items.Count - 1;
}*/
}
private void btnUp_Click(object sender, EventArgs e)
{
if(ImgIndex == -1)
{
MessageBox.Show("No image.");
}
else if (ImgIndex < ImgCount - 1)
{
ImgIndex++;
pictureBox1.Image = img[ImgIndex];
label3.Text = "Image " + (ImgIndex + 1).ToString() + " / " + ImgCount.ToString() ;
}
else
{
MessageBox.Show("This is the last image.");
}
}
private void btnDown_Click(object sender, EventArgs e)
{
if(ImgIndex == -1)
{
MessageBox.Show("No image.");
}
else if (ImgIndex > 0)
{
ImgIndex--;
pictureBox1.Image = img[ImgIndex];
label3.Text = "Image " + (ImgIndex + 1).ToString() + " / " + ImgCount.ToString();
}
else
{
MessageBox.Show("This is the first image.");
}
}
private void btnDeselect_Click(object sender, EventArgs e)
{
listBox1.SelectedIndex = -1;
}
//sets clipboard to selected txt from listbox
private void btnSlct_Click(object sender, EventArgs e)
{
string slctTxt = listBox1.SelectedItem.ToString();
if (slctTxt != null || slctTxt != "")
{
Clipboard.SetText(slctTxt);
}
}
//sets clipboard to selected image
private void btnSlctImg_Click(object sender, EventArgs e)
{
Image slctImg = pictureBox1.Image;
if (slctImg != null)
{
Clipboard.SetImage(slctImg);
}
}
private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
btnSlctTxt.Enabled = true;
}
else
{
btnSlctTxt.Enabled = false;
}
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m); // Process the message
if (m.Msg == WM_DRAWCLIPBOARD)
{
//btnUpdate.PerformClick();
IDataObject iData = Clipboard.GetDataObject(); // Clipboard's data
if (iData.GetDataPresent(DataFormats.Text))
{
string text = (string)iData.GetData(DataFormats.Text); // Clipboard text
listBox1.Items.Add(text);
listBox1.TopIndex = listBox1.Items.Count - 1;
}
else if (iData.GetDataPresent(DataFormats.Bitmap))
{
tmp = (Bitmap)iData.GetData(DataFormats.Bitmap); // Clipboard image
pictureBox1.Image = tmp;
img.Add(tmp);
ImgCount++;
ImgIndex = ImgCount - 1;
label3.Text = "Image " + ImgCount.ToString() + " / " + ImgCount.ToString();
btnSlctImg.Enabled = true;
}
}
}
}
}
Update: It seems the problem is whenever I call the Clipboard.SetImage(...) or Clipboard.SetText(...) - it does it twice. Still don't understand why though.
You have defined a WndProc to catch changes to the clipboard and add the contents to lists.
In your btnSlctImg_Click to do just that:
if (slctImg != null) { Clipboard.SetImage(slctImg); }
So, of course the clipboard is changed, the WndProc is triggered and the currently selected image is added once again to the list you have..
To avoid that you may need to test the lists to see if the image or the text are already in the list. For text this is trivial but for images this is anything but simple. You may have to create and store fingerprints to decide if an image is already in the list.
Here is a post that has examples of creating an MD5 hash for an image.
A simpler trick would be a flag you set in the btnSlctImg_Click right before the Clipboard.SetImage and test and clear in the WndProc. You could still get duplicates, but only if the same data are copied by the user outside of the program..
I wrote a Clipboard utility some time ago and posted it on CodeProject ClipSpy+
I think it will help you with what you are doing!

When getting my emails from my pop3 account the progressBar percentages is getting to 99% why?

What I get is 99% and on the label8 I see 1 and not 0 and the progressBar should get to 100%.
This is the backgroundworker dowork and progresschanged and completed events:
private int numberofallmessages = 0;
private int countMsg = 0;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
OpenPop.Pop3.Pop3Client PopClient = new OpenPop.Pop3.Pop3Client();
PopClient.Connect("mail.bezeqint.net", 110, false);
PopClient.Authenticate("mymeila", "mypass",
OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);
int messageCount = PopClient.GetMessageCount();
numberofallmessages = messageCount;
allMessages = new List<OpenPop.Mime.Message>(messageCount);
for (int i = messageCount; i > 0; i--)
{
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true;
return;
}
allMessages.Add(PopClient.GetMessage(i));
int nProgress = (messageCount - i + 1) * 100 / messageCount;
backgroundWorker1.ReportProgress(nProgress, PopClient.GetMessageCount().ToString() + "/" + i);
}
PopClient.Disconnect();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbt.Value = e.ProgressPercentage;
pbt.Text = e.ProgressPercentage.ToString() + "%";
label8.Text = e.UserState.ToString();
label8.Visible = true;
lstMail.Items.Add(allMessages[countMsg].Headers.Subject);
countMsg += 1;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (closingForm)
this.Close();
}
In the constructor I start the backgroundworker and set the progressBar (pbt) to 0%.
backgroundWorker1.RunWorkerAsync();
pbt.Text = "0%";
This is the progressBar code:
In top of form1:
ProgressBarWithText pbt = new ProgressBarWithText();
In constructor:
pbt.Size = new Size(216, 10);
pbt.Location = new Point(8, 312);
groupBox1.Controls.Add(pbt);
The ProgressBarWithText class:
public class ProgressBarWithText : ProgressBar
{
const int WmPaint = 15;
SizeF TextSize;
PointF TextPos;
bool dontpaint = false;
public ProgressBarWithText()
{
this.DoubleBuffered = true;
this.TextChanged += ProgressBarWithText_TextChanged;
this.SizeChanged += ProgressBarWithText_SizeChanged;
}
public override string Text
{
get { return base.Text; }
set { base.Text = value; }
}
void RecalcTextPos()
{
if (this.IsDisposed == true)
return;
if (string.IsNullOrEmpty(base.Text))
return;
using (var graphics = Graphics.FromHwnd(this.Handle))
{
TextSize = graphics.MeasureString(base.Text, this.Font);
TextPos.X = (this.Width / 2) - (TextSize.Width / 2);
TextPos.Y = (this.Height / 2) - (TextSize.Height / 2);
}
}
void ProgressBarWithText_SizeChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
void ProgressBarWithText_TextChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
if (dontpaint == false)
{
switch (m.Msg)
{
case WmPaint:
using (var graphics = Graphics.FromHwnd(Handle))
graphics.DrawString(base.Text, base.Font, Brushes.Black, TextPos.X, TextPos.Y);
break;
}
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams result = base.CreateParams;
result.ExStyle |= 0x02000000; // WS_EX_COMPOSITED
return result;
}
}
}
The question is if I really downloaded all the emails or there is one left? And how to change/set the code is it will get to 100% and 0 emails downloaded count?
I did a test now I changed the line:
int messageCount = PopClient.GetMessageCount();
To
int messageCount = 5;
And I see in the listView I added to the designer that there are 5 emails.
But what I see in label8 is 7011/1 7011 is the overall emails in the account but for the test I'm downloading only 5. Again it stopped on 1 not 0.
And the progressBar stopped on 80% the text is 80% but I see the green color in the progressBar moved to the end to 100%.
Why it's stopping on 1 and why I see 80%?

Using OpenPop how do i save downloaded emails in message format and also attachments to the hard disk?

Maybe when downloading all emails to create one big file on hard disk of all emails and when running the program over again to parse emails ? Or to save each email to his own message file and make a specific directory for attachments ?
What i want to do is that once i downloaded all emails from server next time i will run my program i will see all the emails without the need to download them over again and if i click a button or using a timer it will download only new emails from the server next time.
This is how i'm downloading the emails today:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenPop;
using OpenPop.Pop3;
using OpenPop.Mime;
namespace Pop3_Emails
{
public partial class Form1 : Form
{
static OpenPop.Pop3.Pop3Client cc = new Pop3Client();
ProgressBarWithText pbt = new ProgressBarWithText();
List<OpenPop.Mime.Message> allMessages;
ListViewNF lvnf;
public Form1()
{
InitializeComponent();
lvnf = new ListViewNF();
lvnf.Location = new Point(250, 18);
lvnf.Size = new Size(474, 168);
lvnf.View = View.Details;
lvnf.Columns.Add("From", 100, HorizontalAlignment.Left);
lvnf.Columns.Add("Subject", 200);
lvnf.Columns.Add("Date", 300);
this.Controls.Add(lvnf);
label8.Visible = false;
pbt.Size = new Size(216, 10);
pbt.Location = new Point(8, 312);
groupBox1.Controls.Add(pbt);
backgroundWorker1.RunWorkerAsync();
pbt.Text = "0%";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private int numberofallmessages = 0;
private int countMsg = 0;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
OpenPop.Pop3.Pop3Client PopClient = new OpenPop.Pop3.Pop3Client();
PopClient.Connect("mail", 110, false);
PopClient.Authenticate("me", "me",
OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);
int messageCount = PopClient.GetMessageCount();
numberofallmessages = messageCount;
allMessages = new List<OpenPop.Mime.Message>(messageCount);
for (int i = messageCount; i > 0; i--)
{
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true;
return;
}
allMessages.Add(PopClient.GetMessage(i));
int nProgress = (messageCount - i + 1) * 100 / messageCount;
backgroundWorker1.ReportProgress(nProgress, PopClient.GetMessageCount().ToString() + "/" + i);
}
PopClient.Disconnect();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbt.Value = e.ProgressPercentage;
pbt.Text = e.ProgressPercentage.ToString() + "%";
pbt.Invalidate();
label8.Text = e.UserState.ToString();
label8.Visible = true;
lvnf.Items.Add(new ListViewItem(new string[]
{
allMessages[countMsg].Headers.From.ToString(), //From Column
allMessages[countMsg].Headers.Subject, //Subject Column
allMessages[countMsg].Headers.DateSent.ToString() //Date Column
}));
countMsg += 1;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (closingForm)
this.Close();
label8.Text = numberofallmessages.ToString() + "/" + "0";
}
public class ProgressBarWithText : ProgressBar
{
const int WmPaint = 15;
SizeF TextSize;
PointF TextPos;
bool dontpaint = false;
public ProgressBarWithText()
{
this.DoubleBuffered = true;
this.TextChanged += ProgressBarWithText_TextChanged;
this.SizeChanged += ProgressBarWithText_SizeChanged;
}
public override string Text
{
get { return base.Text; }
set { base.Text = value; }
}
void RecalcTextPos()
{
if (this.IsDisposed == true)
return;
if (string.IsNullOrEmpty(base.Text))
return;
using (var graphics = Graphics.FromHwnd(this.Handle))
{
TextSize = graphics.MeasureString(base.Text, this.Font);
TextPos.X = (this.Width / 2) - (TextSize.Width / 2);
TextPos.Y = (this.Height / 2) - (TextSize.Height / 2);
}
}
void ProgressBarWithText_SizeChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
void ProgressBarWithText_TextChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
if (dontpaint == false)
{
switch (m.Msg)
{
case WmPaint:
using (var graphics = Graphics.FromHwnd(Handle))
graphics.DrawString(base.Text, base.Font, Brushes.Black, TextPos.X, TextPos.Y);
break;
}
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams result = base.CreateParams;
result.ExStyle |= 0x02000000; // WS_EX_COMPOSITED
return result;
}
}
}
private bool closingForm = false;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!closingForm && MessageBox.Show("You sure?", "Form1", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
else if (backgroundWorker1.IsBusy)
{
e.Cancel = true;
closingForm = true;
if (!backgroundWorker1.CancellationPending)
backgroundWorker1.CancelAsync();
}
}
class ListViewNF : System.Windows.Forms.ListView
{
public ListViewNF()
{
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
protected override void OnNotifyMessage(System.Windows.Forms.Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}
}
}
The problem is that now i'm adding the emails parts to ListView control and also adding the messages to the List allMessages. But i never save the emails and attachments to the hard disk so each time i will run my program over again it will download all the emails again over 7000 emails.

C# Keep picturebox in form1

I have a picturebox in windows form application that has the ability to move with arrowkeys. I want it to have certain limits to where it can go, specifically in the form. How do I do this? My class to move the target is below:
namespace AmazingPaintball
{
class Target
{
private Point p;
public Target(Point myPoi)
{
p = myPoi;
}
public Point Move(Keys key)
{
if (key == Keys.Left)
{
p.Offset(-50, 0);
}
else if (key == Keys.Right)
{
p.Offset(50, 0);
}
else if (key == Keys.Up)
{
p.Offset(0, -50);
}
else if (key == Keys.Down)
{
p.Offset(0, 50);
}
return p;
}
}
}
Below is the form1:
namespace AmazingPaintball
{
public partial class Form1 : Form
{
Random positionX = new Random();
Random positionY = new Random();
Target einstein;
int count = 0;
Paintballs pBalls = new Paintballs();
Stopwatch stopwatch = new Stopwatch();
SoundPlayer wavPlayer = new SoundPlayer(#"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\Resources\singlegunshot.wav");
SoundPlayer wavPlayer2 = new SoundPlayer(#"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\bin\Debug\Resources\Applause.wav");
public Form1()
{
InitializeComponent();
Point point = new Point(positionX.Next(0, 638), positionY.Next(0, 404));
einstein = new Target(point);
ptrEinstein.Location = point;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
pBalls.paint(e.Graphics);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
ptrEinstein.Location = einstein.Move(e.KeyData);
pictureBox1.Update();
pictureBox1.Refresh();
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
wavPlayer.Play();
pBalls.add(e.Location);
pictureBox1.Refresh();
count++;
}
private void Form1_Load(object sender, EventArgs e)
{
stopwatch.Start();
}
private void ptrEinstein_MouseClick(object sender, MouseEventArgs e)
{
count++;
ptrEinstein.Image = Properties.Resources.AlbertEinsteinTongue;
stopwatch.Stop();
wavPlayer2.Play();
MessageBox.Show("It took " + count + " shots and " + stopwatch.Elapsed + " seconds to hit the target");
wavPlayer2.Stop();
ptrEinstein.Image = Properties.Resources.AlbertEinsteinFace;
count = 0;
stopwatch.Reset();
stopwatch.Start();
}
}
}
The picturebox is ptrEinstein and it is able to move in the form1_keydown event.
When you're moving the picture box, first check to make sure where you're moving it to is inside the form. E.g. check if the new X + the width of the picture box is less than the width of the form, etc.
This will be incomplete because we do not have your code, but you should compare the clientSize properties to the picturebox location (taking into account the size of the picturebox):
PictureBox pb = new PictureBox();
int newX = oldX + xOffset; // xOffset is whatever you're incrementing x by
int newY = oldY + yOffset; // yOffset is whatever you're incrementing y by
if (newX < 0) {
newX = 0;
} else if (newX > this.ClientSize.Width - pb.Width) {
newX = this.ClientSize.Width - pb.Width;
}
if (newY < 0) {
newY = 0;
} else if (newY > this.ClientSize.Height - pb.Height) {
newY = this.ClientSize.Height - pb.Height;
}
// New point to move it to
Point newP = new Point(newX, newY);

Creating a custom Multi-Line Listbox

In the creation of some apps, a list-box with multiple lined content is preferred. Since listboxes have no such function, the creation of a custom control is needed. For this case, I'm working on a compiler app that the user can load an import and export C# prefab into the program to manipulate data. To see this compiler in action, you can check out my previous post here. For this instance, I want a debug log of any errors to be outputted into the listbox. Since some errors contain multiple lines, some of which are rather long, I read up and generated a Listbox of Textbox items.
The most current copy of this can be found on pastebin.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DataStripper
{
public partial class MultiLineListView : System.Windows.Forms.ListBox
{
public MultiLineListView()
{
//InitializeComponent();
this.DrawMode = DrawMode.OwnerDrawVariable;
this.ScrollAlwaysVisible = true;
tbox.Hide();
tbox.mllb = this;
Controls.Add(tbox);
}
protected override void OnMeasureItem(MeasureItemEventArgs e)
{
if (Site != null)
return;
if (e.Index > -1)
{
string s = Items[e.Index].ToString();
float best = 0;
foreach (string line in s.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
float chk = e.Graphics.MeasureString(line, Font, Width).Width;
if (chk > best)
best = chk;
}
SizeF sf = e.Graphics.MeasureString(s, Font, Width);
int htex = 1;//(e.Index == 0) ? 15 : 10;
e.ItemHeight = (int)(sf.Height*Items.Count) + htex;
e.ItemWidth = (int)best;
/*NTextBox i = (NTextBox)Items[e.Index];
e.ItemHeight = i.Height;
e.ItemWidth = i.Width;*/
}
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (Site != null)
return;
if (e.Index > -1)
{
string s = Items[e.Index].ToString();
if ((e.State & DrawItemState.Focus) == 0)
{
e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window), e.Bounds);
e.Graphics.DrawString(s, Font, new SolidBrush(SystemColors.WindowText),
e.Bounds);
e.Graphics.DrawRectangle(new Pen(SystemColors.Highlight), e.Bounds);
}
else
{
e.Graphics.FillRectangle(new SolidBrush(SystemColors.Highlight), e.Bounds);
e.Graphics.DrawString(s, Font, new SolidBrush(SystemColors.HighlightText),
e.Bounds);
}
}
}
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
{
int index = IndexFromPoint(e.X, e.Y);
if (index != ListBox.NoMatches &&
index != 65535)
{
/*if (e.Button == MouseButtons.Right)
{
SelectedIndex = index;
Focus();
//tbox.index = index;
}*/
/*if (e.Button == MouseButtons.Right)
{
string s = Items[index].ToString();
Rectangle rect = GetItemRectangle(index);
tbox.Location = new Point(rect.X, rect.Y);
tbox.Size = new Size(rect.Width, rect.Height);
tbox.Text = s;
tbox.index = index;
tbox.SelectAll();
tbox.Show();
tbox.Focus();
}*/
}
base.OnMouseUp(e);
}
NTextBox tbox = new NTextBox();
class NTextBox : TextBox
{
public MultiLineListView mllb;
public int index = -1;
bool errshown = false;
bool brementer = false;
public NTextBox()
{
Multiline = true;
MaxLength = 2147483647;
MaximumSize = new System.Drawing.Size(0, 0);
WordWrap = false;
ScrollBars = ScrollBars.Both;
AcceptsReturn = true;
AcceptsTab = true;
}
protected override void OnKeyUp(KeyEventArgs e)
{
if (brementer)
{
Text = "";
brementer = false;
}
base.OnKeyUp(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
}
protected override void OnLostFocus(System.EventArgs e)
{
if (Text.Trim() == "")
{
if (!errshown)
{
MessageBox.Show(
"Cannot enter NULL string as item!",
"Fatal error!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
errshown = false;
}
else
{
errshown = false;
mllb.Items[index] = Text;
Hide();
}
base.OnLostFocus(e);
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyData == Keys.F2)
{
int index = SelectedIndex;
if (index == ListBox.NoMatches ||
index == 65535)
{
if (Items.Count > 0)
index = 0;
}
if (index != ListBox.NoMatches &&
index != 65535)
{
string s = Items[index].ToString();
Rectangle rect = GetItemRectangle(index);
tbox.Location = new Point(rect.X, rect.Y);
tbox.Size = new Size(rect.Width, rect.Height);
tbox.Text = s;
tbox.index = index;
tbox.SelectAll();
tbox.Show();
tbox.Focus();
}
}
base.OnKeyDown(e);
}
}
}
The difficulty I'm having, is that, even though I've set the textbox as it should be, the list view item still seems to be limiting content to TextWrap, and a maximum of 7.5 lines.
Image Reference http://imageshack.us/a/img819/9345/5nh4.png
On line 32 foreach (string line in s.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) I try to find the length of the longest line of text in the string to return in the OnMeasureItem override, but it refuses to go in excess of the assumed limit. Any help would be greatly appreciated.
You should take a look at a control called GlacialList. you can do such thing easily. Latest versions are not free but i used to use version 1.3. If you get to it there is a property that allow you to put ANY control inside a list cell. just add multiline textbox and your good to go
It may not be an option for you but if you want more Advanced UI features why not just switch to WPF where you get this built-in?

Categories

Resources