Getting a InvalidOperationException is program.cs when running a new form - c#

I am making a twitch chat bot and for some reason I will sometimes get errors saying i am making cross-thread calls to an object, but I cant find anything that could be causing this, I have tried making a try-catch statement around the application.run statement but that doesn't fix it
Program.cs:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); // the error occurs here
}
Form1.cs:
#region variables
#region itunes variables
iTunesApp player = new iTunesApp();
#endregion
static Irc irc;
string nickname;
String message;
String rawMessage;
int dVolume = 100;
string fadeDir = "";
int fadeSpeed = 2;
#region banned_words
String[] bannedWords = { dont want to put these on this website :P};
#endregion
Thread Messages;
Form2 f2;
WebClient Client = new WebClient();
List<String> viewers;
#endregion
public Form1()
{
InitializeComponent();
player.OnPlayerPlayEvent += new _IiTunesEvents_OnPlayerPlayEventEventHandler(player_OnPlayerPlayingTrackChangedEvent);
irc = new Irc("irc.twitch.tv", 6667, "ZChembot", "oauth");
irc.joinRoom("zchem");
irc.send("Starting up...");
irc.sendIrc("CAP REQ :twitch.tv/membership");
Messages = new Thread(new ThreadStart(getMessages));
Messages.IsBackground = true;
Messages.Start();
fade.Enabled = true;
f2 = new Form2(this);
f2.Show();
getNames.Enabled = true;
}
public void player_OnPlayerPlayingTrackChangedEvent(object iTrack)
{
if (InvokeRequired)
{
this.Invoke(new Action<object>(player_OnPlayerPlayingTrackChangedEvent), new object[] { iTrack });
return;
}
IITTrack track = new iTunesApp().CurrentTrack;
if (String.IsNullOrEmpty(sound))
{
song.Text = "Song: " + track.Name;
StreamWriter file = new StreamWriter(#"c:\users\ben\desktop\twitch\Song.txt");
file.WriteLine(track.Name);
file.Close();
artist.Text = "Artist: " + track.Artist;
album.Text = "Album: " + track.Album;
}
f2.enableTimer();
f2.update();
}
public void Destroy()
{
player.OnPlayerPlayEvent -= player_OnPlayerPlayingTrackChangedEvent;
Marshal.ReleaseComObject(player);
}
#region threads
private void getMessages()
{
while (true)
{
message = irc.readMessage();
if (checkBox1.Checked)
{
updateChat("$NOTICE", message, Color.Purple);
}
rawMessage = message;
#region PRIVMSG
if (!String.IsNullOrEmpty(message))
{
if (message.Contains("PRIVMSG #zchem"))
{
nickname = rawMessage.Substring(1, message.IndexOf("!") - 1);
int start = message.IndexOf("#zchem") + 8;
String str = message.Substring(start);
message = str;
updateChat(nickname, message, Color.Black);
}
#endregion
#region notices
//successful connection
if (message.StartsWith(":tmi.twitch.tv 001 zchembot :Welcome, GLHF!"))
{
updateChat("$NOTICE", "successfully connected to the chat", Color.Green);
}
//the server pings the bot
if (message.StartsWith("PING tmi.twitch.tv"))
{
updateChat("$NOTICE", "Recieved a ping from the server", Color.Blue);
irc.sendIrc("PONG");
}
#endregion
#region play
if (message.StartsWith("!play"))
player.Play();
#endregion
#region volume up
if (message.StartsWith("!volume up"))
{
if (IsDigitsOnly(message.Substring(message.IndexOf(" ") + 1, message.Length)))
{
player.SoundVolume += int.Parse(message.Substring(message.IndexOf(" ") + 1, message.Length));
irc.send("The music volume has been changed to " + player.SoundVolume + "%");
}
}
#endregion
#region volume down
if (message.StartsWith("!volume down"))
{
if (IsDigitsOnly(message.Substring(message.IndexOf(" ", 10) + 1, message.Length)))
{
player.SoundVolume -= int.Parse(message.Substring(message.IndexOf(" ") + 1, message.Length));
irc.send("The music volume has been changed to " + player.SoundVolume + "%");
}
}
#endregion
#region vurrent volume
if (message.StartsWith("!current volume"))
{
irc.send("The current music volume is at " + player.SoundVolume + "%");
}
#endregion
#region join
if (rawMessage.EndsWith("JOIN #zchem"))
{
//detects when users join the channel
nickname = rawMessage.Substring(1, message.IndexOf("!") - 1);
irc.send("Hello, " + nickname + "!");
}
#endregion
#region part
if (rawMessage.EndsWith("PART #zchem"))
{
nickname = rawMessage.Substring(1, message.IndexOf("!") - 1);
irc.send(nickname + "has left the chat");
MessageBox.Show(nickname + "has left the chat");
}
#endregion
}
Thread.Sleep(100);
}
}
public void fade_Tick(object sender, EventArgs e)
{
if (this.Visible)
{
if (fadeDir.Equals("up"))
{
player.Play();
if (player.SoundVolume + fadeSpeed > dVolume)
player.SoundVolume = dVolume;
else
player.SoundVolume += fadeSpeed;
}
else if (fadeDir.Equals("down"))
{
if (player.SoundVolume - fadeSpeed < 0)
player.SoundVolume = 0;
else
player.SoundVolume -= fadeSpeed;
}
else if (player.SoundVolume == dVolume || player.SoundVolume == 0)
fadeDir = "";
if (player.SoundVolume == 0)
player.Pause();
}
}
#endregion
#region itunes events
private void playpause_Click(object sender, EventArgs e)
{
if (playpause.Text.Equals("❚❚"))
{
fadeDir = "down";
playpause.Text = "►";
}
else
{
fadeDir = "up";
playpause.Text = "❚❚";
}
}
private void nextSong_Click(object sender, EventArgs e)
{
player.NextTrack();
}
private void lastSong_Click(object sender, EventArgs e)
{
player.PreviousTrack();
}
private void showArt_CheckedChanged(object sender, EventArgs e)
{
if (showArt.Checked)
{
f2.Show();
}
else
{
f2.Hide();
}
}
private void soundDelay_TextChanged(object sender, EventArgs e)
{
if (!IsDigitsOnly(soundDelay.Text))
{
soundDelay.Text = "5";
}
}
#endregion
#region form events
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Destroy();
}
#endregion
bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
public void updateChat(string nickname, string message, Color color)
{
String text;
String time = DateTime.Now.ToShortTimeString();
time = time.Substring(0, time.Length - 3);
if (InvokeRequired)
{
this.Invoke(new Action<string, string, Color>(updateChat), new object[] { nickname, message, color });
return;
}
if (nickname.Equals("$NOTICE"))
nickname = "";
else
nickname += ": ";
text = ("[" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + "] " + nickname + message + "\n");
chat.SelectionStart = chat.TextLength;
chat.SelectionLength = 0;
chat.SelectionColor = color;
chat.AppendText(text);
}
}
Irc.cs:
private string username;
public TcpClient tcpClient;
private StreamReader inputStream;
private StreamWriter outputStream;
public Irc(string ip, int port, string username, string password)
{
this.username = username;
tcpClient = new TcpClient(ip, port);
inputStream = new StreamReader(tcpClient.GetStream());
outputStream = new StreamWriter(tcpClient.GetStream());
outputStream.WriteLine("PASS " + password);
outputStream.WriteLine("NICK " + username);
outputStream.WriteLine("USER " + username + " 8 * :" + username);
outputStream.Flush();
}
public void joinRoom(string channel)
{
outputStream.WriteLine("JOIN #" + channel);
outputStream.Flush();
}
public void sendIrc(string message)
{
outputStream.WriteLine(message);
outputStream.Flush();
}
public void send(string message)
{
//sendIrc(":" + username + "!" + username + "#" + ".tmi.twitch.tv PRIVMSG #zchem :" + message);
}
public string readMessage()
{
string message = inputStream.ReadLine();
Console.WriteLine(message);
return message;
}
}
}
Form2.cs:
Form1 f1;
public Form2(Form1 f1)
{
InitializeComponent();
this.f1 = f1;
timer1.Enabled = true;
}
public void update()
{
IITTrack track = player.CurrentTrack;
IITArtworkCollection Art1 = track.Artwork;
IITArtwork Art2 = Art1[1];
Art2.SaveArtworkToFile(#"c:\users\ben\desktop\twitch\Album.png");
Stream s = File.Open(#"c:\users\ben\desktop\twitch\Album.png", FileMode.Open);
Image temp = Image.FromStream(s);
s.Close();
this.BackgroundImage = resize(temp);
if (!f1.Visible)
{
System.Environment.Exit(1);
}
}
static public Bitmap Copy(Bitmap srcBitmap, Rectangle section)
{
// Create the new bitmap and associated graphics object
Bitmap bmp = new Bitmap(section.Width, section.Height);
Graphics g = Graphics.FromImage(bmp);
// Draw the specified section of the source bitmap to the new one
g.DrawImage(srcBitmap, 0, 0, section, GraphicsUnit.Pixel);
// Clean up
g.Dispose();
// Return the bitmap
return bmp;
}
public static IEnumerable<Color> GetPixels(Bitmap bitmap)
{
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
Color pixel = bitmap.GetPixel(x, y);
yield return pixel;
}
}
}
#region enable click-through
public enum GWL
{
ExStyle = -20
}
public enum WS_EX
{
Transparent = 0x20,
Layered = 0x80000
}
public enum LWA
{
ColorKey = 0x1,
Alpha = 0x2
}
[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
public static extern int GetWindowLong(IntPtr hWnd, GWL nIndex);
[DllImport("user32.dll", EntryPoint = "SetWindowLong")]
public static extern int SetWindowLong(IntPtr hWnd, GWL nIndex, int dwNewLong);
[DllImport("user32.dll", EntryPoint = "SetLayeredWindowAttributes")]
public static extern bool SetLayeredWindowAttributes(IntPtr hWnd, int crKey, byte alpha, LWA dwFlags);
protected void enable()
{
int wl = GetWindowLong(this.Handle, GWL.ExStyle);
wl = wl | 0x80000 | 0x20;
SetWindowLong(this.Handle, GWL.ExStyle, wl);
SetLayeredWindowAttributes(this.Handle, 0, 128, LWA.Alpha);
}
protected void disable()
{
SetWindowLong(this.Handle, GWL.ExStyle, 0);
SetLayeredWindowAttributes(this.Handle, 0, 128, LWA.Alpha);
}
#endregion
#region image stuph
public Size GenerateImageDimensions(int currW, int currH, int destW, int destH)
{
//double to hold the final multiplier to use when scaling the image
double multiplier = 0;
//string for holding layout
string layout;
//determine if it's Portrait or Landscape
if (currH > currW) layout = "portrait";
else layout = "landscape";
switch (layout.ToLower())
{
case "portrait":
//calculate multiplier on heights
if (destH > destW)
{
multiplier = (double)destW / (double)currW;
}
else
{
multiplier = (double)destH / (double)currH;
}
break;
case "landscape":
//calculate multiplier on widths
if (destH > destW)
{
multiplier = (double)destW / (double)currW;
}
else
{
multiplier = (double)destH / (double)currH;
}
break;
}
//return the new image dimensions
return new Size((int)(currW * multiplier), (int)(currH * multiplier));
}
private Image resize(Image img)
{
try
{
//calculate the size of the image
Size imgSize = GenerateImageDimensions(img.Width, img.Height, this.Width, this.Height);
//create a new Bitmap with the proper dimensions
Bitmap finalImg = new Bitmap(img, imgSize.Width, imgSize.Height);
//create a new Graphics object from the image
Graphics gfx = Graphics.FromImage(img);
//clean up the image (take care of any image loss from resizing)
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
//set the new image
return finalImg;
}
catch (System.Exception e)
{
MessageBox.Show(e.Message);
return null;
}
}
#endregion
private void timer1_Tick(object sender, EventArgs e)
{
this.Location = new Point(1920 - this.Width, 1080 - this.Height - 40);
if (Cursor.Position.X >= this.Location.X && Cursor.Position.X <= this.Location.X + this.Width && Cursor.Position.Y >= this.Location.Y && Cursor.Position.Y <= this.Location.Y + this.Height)
{
enable();
}
else
{
disable();
}
}
private void timer2_Tick(object sender, EventArgs e)
{
IITTrack track = player.CurrentTrack;
double max = track.Duration;
double val = player.PlayerPosition;
double prog = (int)(val/max * 100);
progressBar1.Value = (int)prog;
}
public void enableTimer()
{
timer2.Enabled = true;
}
}

As the debugger said, you're doing cross-thread calls.
The interface can only be updated from the main thread, and you're updating it from a secondary one.
You start a new thread on
Messages = new Thread(new ThreadStart(getMessages));
And in the getMessages function you are updating your form, so that are cross-thread calls.
If you Invoke your calls to updateChat and the MessageBox'es I think you will have enough, if no, then revise if some other function calls inside getMessages also update the interface.
Cheers.

Try this in constructor of form from which you are creating thread
Form1.CheckForIllegalCrossThreadCalls = false;
after this line InitializeComponent();
Note: This is dangerous
Try delegate methods for safe Thread calls.

Related

C# invalid stream Image.FromStream()

I try to make an screenshare application using udp sockets. I first record screenshots on a list than i save bitmaps to memorystream and send with 2 packages. I can merge them on client/server but it doesnt work.
I share my codes it starts to listen at button10 click and start so share at button8click
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace OKAYOKAY
{
public class DataManager
{
public String IPADRESS;
public int PORT;
Socket socket;
IPEndPoint ep,karsiEp;
int lastBytesRead = 0;
bool KEEPRECEIVE,ISCONNECTED;
public List<byte[]> BUFFERREAD = new List<byte[]>();
public List<byte[]> BUFFERSEND = new List<byte[]>();
MemoryStream ms = new MemoryStream();
public DataManager(string IPADRESS, int pORT)
{
IPADRESS = IPADRESS;
PORT = pORT;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
ep = new IPEndPoint(IPAddress.Parse(IPADRESS), PORT);
socket.Bind(ep);
}
public bool connect(string ip,int port)
{
karsiEp = new IPEndPoint(IPAddress.Parse(ip), port);
socket.Connect(karsiEp);
ISCONNECTED = socket.Connected;
return socket.Connected;
}
public void startListen()
{
KEEPRECEIVE = true;
Task.Run(() =>
{
byte[] buf = new byte[64000];
int i = 0;
while (KEEPRECEIVE)
{
if (socket.Receive(buf) > 0)
{
BUFFERREAD.Add(buf);
Form1.writeConsole("veri alındı !");
}
if(i % 2 == 1)
{
bool SONMUKONTROL,SECONDBOS;
byte[] F = BUFFERREAD[i - 1];
byte[] S = BUFFERREAD[i];
int SONI=0;
SECONDBOS = false;
for (int j = 0; j <S.Length; j++) // TO FIND IF WHERE FILE ENDS IN ARRAY
{
if (S[j] == 0)
{
SONMUKONTROL = true;
for (int k = j; k < S.Length; k++)
{
if (k - j == 10)
break;
if (S[k] != 0)
{
SONMUKONTROL = false;
break;
}
}
if(SONMUKONTROL)
{
SONI = j;
break;
}
}
}
if(SONI == 0)
{
SECONDBOS = true;
for (int j = 0; j < F.Length; j++)
{
if (F[j] == 0)
{
SONMUKONTROL = true;
for (int k = j; k < F.Length; k++)
{
if (k - j == 10)
break;
if (F[k] != 0)
{
SONMUKONTROL = false;
break;
}
}
if (SONMUKONTROL)
{
SONI = j;
break;
}
}
}
}
if (!SECONDBOS)
SONI += 64000;
byte[] FINAL = new byte[SONI];
for (int j = 0; j < SONI; j++)
{
if (j < 64000)
{
FINAL[j] = F[j];
}
else
FINAL[j] = S[j - 64000];
}
ms.Write(FINAL);
File.WriteAllBytes("temp/a"+i+".jpeg", FINAL);
ms.SetLength(0);
}
i++;
}
});
}
public void sendData(byte[] array)
{
socket.Send(array);
}
public void stopREC()
{
KEEPRECEIVE = false;
}
}
}
Here is my form code. It start to share at button8 click function
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using static System.Windows.Forms.DataFormats;
namespace OKAYOKAY
{
public partial class Form1 : Form
{
DateTime start, end;
bool keeprecord,keepsharing;
int totalframes=0;
DataManager dataManager;
static Bitmap newImage = new Bitmap(1280, 720);
object o = new object();
ImageConverter converter = new ImageConverter();
public static List<Bitmap> IMAGEBUFFER = new List<Bitmap>();
public static List<MemoryStream> IMAGES = new List<MemoryStream>();
public static TextBox console;
static int IMAGESETCOUNT = 0;
static PictureBox video;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
console = textBox3;
video = pictureBox1;
}
void RECORD()
{
start = DateTime.Now;
Rectangle bounds = Screen.GetBounds(Point.Empty);
DateTime s1;
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
long mseconds,dtime;
float avgDT = 30;
while (keeprecord)
{
mseconds = DateTime.Now.Millisecond;
using(Graphics g = Graphics.FromImage(bitmap))
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
//ScaleImage(bitmap, 1280, 720).Save("temp/test"+totalframes+".jpg", ImageFormat.Jpeg);
lock(o)
{
IMAGEBUFFER.Add(ScaleImage(bitmap, 1280, 720));
/*MemoryStream ms = new MemoryStream();
ScaleImage(bitmap, 1280, 720).Save(ms, ImageFormat.Jpeg);
IMAGES.Add(ms);
ms.Flush();*/
}
totalframes++;
dtime = DateTime.Now.Millisecond - mseconds;
if(totalframes%30 ==0)
label2.Text = (1000/dtime).ToString();
}
end = DateTime.Now;
}
static Bitmap ScaleImage(Bitmap bmp, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / bmp.Width;
var ratioY = (double)maxHeight / bmp.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(bmp.Width * ratio);
var newHeight = (int)(bmp.Height * ratio);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(bmp, 0, 0, newWidth, newHeight);
return newImage;
}
void fotokoy()
{
int i = 0;
int ms;
if (keeprecord)
ms=(DateTime.Now-start).Milliseconds/totalframes;
else
ms = (end - start).Milliseconds / totalframes;
label2.Text = ms.ToString();
while(true)
{
while (i < totalframes)
{
try
{
//pictureBox1.Image = Image.FromFile("temp/test" + i + ".jpg");
//i++;
pictureBox1.Image = IMAGEBUFFER[0];
//pictureBox1.Image = Image.FromStream(IMAGES[0]);
lock(o)
{
//IMAGES.RemoveAt(0);
IMAGEBUFFER.RemoveAt(0);
}
Thread.Sleep(30);
i++;
if(totalframes%100 == 0)
GC.Collect();
}
catch(Exception e)
{
}
}
Thread.Sleep(1000);
continue;
}
}
private void button1_Click(object sender, EventArgs e)
{
keeprecord = true;
Thread thr = new Thread(new ThreadStart(RECORD));
thr.Start();
}
private void button2_Click(object sender, EventArgs e)
{
keeprecord=false;
}
private void button3_Click(object sender, EventArgs e)
{
Thread thrr = new Thread(new ThreadStart(fotokoy));
thrr.Start();
}
public static void setImage(Image img)
{
IMAGESETCOUNT++;
video.Image = img;
if(IMAGESETCOUNT % 100 == 0)
{
GC.Collect();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static void writeConsole(string a)
{
console.AppendText(a);
console.AppendText(Environment.NewLine);
}
private void button4_Click(object sender, EventArgs e)
{
writeConsole("PORT DINLENIYOR : " + textBox2.Text);
dataManager = new DataManager(textBox1.Text, int.Parse(textBox2.Text));
try
{
if (dataManager.connect(textBox5.Text, int.Parse(textBox4.Text)))
{
writeConsole("BAGLANTI SAGLANDI !");
}
else
writeConsole("BAGLANTI SAGLANAMADI ! !");
}
catch (Exception ee)
{
writeConsole(ee.Message);
}
}
private void button5_Click(object sender, EventArgs e)
{
dataManager = new DataManager(textBox1.Text, int.Parse(textBox2.Text));
try
{
if (dataManager.connect(textBox5.Text,int.Parse(textBox4.Text)))
{
writeConsole("BAGLANTI SAGLANDI !");
}
else
writeConsole("BAGLANTI SAGLANAMADI ! !");
}
catch(Exception ee)
{
writeConsole(ee.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
dataManager.sendData(Encoding.ASCII.GetBytes("SA MERHABA"));
}
private void button7_Click(object sender, EventArgs e)
{
if(dataManager.BUFFERREAD.Count > 0)
{
writeConsole(Encoding.ASCII.GetString(dataManager.BUFFERREAD[0]));
}
}
private void button10_Click(object sender, EventArgs e)
{
dataManager.startListen();
}
public byte[] ImageToByte(Image image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Jpeg);
return ms.ToArray();
}
}
private void button11_Click(object sender, EventArgs e)
{
dataManager.stopREC();
}
private void button9_Click(object sender, EventArgs e)
{
}
private void button8_Click(object sender, EventArgs e) // START SHARING
{
keepsharing = true;
MemoryStream ms = new MemoryStream();
Task.Run(() =>
{
int i = 0;
while(keepsharing)
{
while(i<totalframes)
{
//IMG = ImageToByte(Image.FromStream(IMAGES[0]));
lock (o)
{
IMAGEBUFFER[0].Save(ms, ImageFormat.Jpeg);
IMAGEBUFFER.RemoveAt(0);
//IMAGES.RemoveAt(0);
}
byte[] IMG = ImageToByte(Image.FromStream(ms));
byte[] F= new byte[64000], S= new byte[64000];
for (int j = 0; j < IMG.Length; j++)
{
if (j < 64000)
{
F[j] = IMG[j];
}
else
S[j-64000] = IMG[j];
}
dataManager.sendData(F);
dataManager.sendData(S);
writeConsole(IMG.Length.ToString());
ms.SetLength(0);
i++;
}
Thread.Sleep(50);
}
writeConsole("Paylasımdan cıktı !");
});
}
private void timer1_Tick(object sender, EventArgs e)
{
}
}
}
If there is any other way i can change the way i do.

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%?

How to lower the terrain using OpenSimulator?

I made a simulation in OpenSimulator. I changed the terrain to resemble that of Atlantis and used the OpenSimTide module to have the tide cause the disappearance of Atlantis.
Now the OpenSimTide module works, but for some reason I just can't find out how I make the terrain go lower whenever the tide reaches a specific level. How can I achieve this?
Here's what i have up until now:
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse;
using Mono.Addins;
[assembly: Addin("OpenSimTide", "0.2")]
[assembly: AddinDependency("OpenSim.Region.Framework",
OpenSim.VersionInfo.VersionNumber)]
namespace TideModule
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OpenSimTide")]
public class OpenSimTide : INonSharedRegionModule
{
#region Fields
private static readonly ILog m_log = LogManager.GetLogger (MethodBase.GetCurrentMethod ().DeclaringType);
public string Name { get { return m_name; } }
public Type ReplaceableInterface { get { return null; } }
private const int TICKS_PER_SECOND = 10000000;
public string m_name = "OpenSimTide";
private string m_regionConfigDir = "";
private uint m_frame = 0;
private int m_frameUpdateRate = 100;
private bool m_enabled = false;
private bool m_ready = false;
private float m_tideLevel = 20.0f; //current water level in m
private float m_lowTide = 18.0f; //low water level in m
private float m_highTide = 22.0f; //high water level in m
private ulong m_cycleTime = 3600; //low->high->low time in seconds
private DateTime m_lowTideTime = new DateTime(); // datetime indicating when next low tide will be
private DateTime m_highTideTime = new DateTime(); // datetime indicating when next hightide will be
private bool m_tideDirection = true; // which direction is the tide travelling, 'Coming In'(true) or 'Going Out'(false)
private bool m_lastTideDirection = true;
private bool m_tideInfoDebug = false; //do we chat the tide to the OpenSim console?
private bool m_tideInfoBroadcast = true; //do we chat the tide to the region?
private int m_tideInfoChannel = 5555; //chat channel for all tide info
private int m_tideLevelChannel = 5556; //chat channel for just the tide level in m
private int m_tideAnnounceCount = 5; //how many times do we announce the turning tide
private int m_tideAnnounceCounter = 0; //counter we use to count announcements of low or high tide
private string m_tideAnnounceMsg = "";
private ITerrainChannel m_channel;
public scene m_scene;
public IConfigSource m_config;
public RegionInfo m_regionInfo;
public Dictionary<string, Scene> mScene = new Dictionary<string, Scene> ();
public Vector3 m_shoutPos = new Vector3(128f, 128f, 30f);
#endregion
#region IRegionModuleBase implementation
public void Initialise (IConfigSource source)
{
m_config = source;
}
public void Close ()
{
if (m_enabled) {
m_scene.EventManager.OnFrame -= TideUpdate;
}
}
public void AddRegion (Scene scene)
{
IConfig cnf;
m_log.InfoFormat("[{0}]: Adding region '{1}' to this module", m_name, scene.RegionInfo.RegionName);
cnf = m_config.Configs["Startup"];
m_regionConfigDir = cnf.GetString("regionload_regionsdir", Path.Combine(Util.configDir(), "bin/Regions/"));
cnf = m_config.Configs[scene.RegionInfo.RegionName];
if(cnf == null)
{
m_log.InfoFormat("[{0}]: No region section [{1}] found in addon-modules/{2}/config/*.ini configuration files.", m_name, scene.RegionInfo.RegionName, m_name);
//string moduleConfigFile = Path.Combine(Util.configDir(),m_name + ".ini");
string moduleConfigFile = Path.Combine(m_regionConfigDir, "Regions.ini");
try
{
m_log.InfoFormat("[{0}]: Checking {1} for [{2}] section containing valid config keys", m_name, moduleConfigFile, scene.RegionInfo.RegionName);
m_config = new IniConfigSource(moduleConfigFile);
cnf = m_config.Configs[scene.RegionInfo.RegionName];
}
catch (Exception)
{
cnf = null;
}
if (cnf == null)
{
m_log.InfoFormat("[{0}]: No region section [{1}] found in configuration {2}. Tide in this region is set to Disabled", m_name, scene.RegionInfo.RegionName, moduleConfigFile);
m_enabled = false;
return;
}
}
m_enabled = cnf.GetBoolean("TideEnabled", false);
if (m_enabled)
{
m_frameUpdateRate = cnf.GetInt("TideUpdateRate", 150);
m_lowTide = cnf.GetFloat("TideLowWater", 18.0f);
m_highTide = cnf.GetFloat("TideHighWater", 22.0f);
m_cycleTime = (ulong)cnf.GetInt("TideCycleTime", 3600);
m_tideInfoDebug = cnf.GetBoolean("TideInfoDebug", false);
m_tideInfoBroadcast = cnf.GetBoolean("TideInfoBroadcast", true);
m_tideInfoChannel = cnf.GetInt("TideInfoChannel", 5555);
m_tideLevelChannel = cnf.GetInt("TideLevelChannel", 5556);
m_tideAnnounceCount = cnf.GetInt("TideAnnounceCount", 5);
m_log.InfoFormat("[{0}]: Enabled with an update rate every {1} frames, Low Water={2}m, High Water={3}m, Cycle Time={4} secs", m_name, m_frameUpdateRate, m_lowTide, m_highTide, m_cycleTime);
m_log.InfoFormat("[{0}]: Info Channel={1}, Water Level Channel={2}, Info Broadcast is {3}, Announce Count={4}", m_name, m_tideInfoChannel, m_tideLevelChannel, m_tideInfoBroadcast, m_tideAnnounceCounter);
m_frame = 0;
m_ready = true; // Mark Module Ready for duty
m_shoutPos = new Vector3(scene.RegionInfo.RegionSizeX / 2f, scene.RegionInfo.RegionSizeY / 2f, 30f);
scene.EventManager.OnFrame += TideUpdate;
m_scene = scene;
}
else
{
m_log.InfoFormat("[{0}]: Tide in this region is set to Disabled", m_name);
}
}
public void RemoveRegion (Scene scene)
{
m_log.InfoFormat("[{0}]: Removing region '{1}' from this module", m_name, scene.RegionInfo.RegionName);
if (m_enabled)
{
scene.EventManager.OnFrame -= TideUpdate;
}
}
public void RegionLoaded (Scene scene)
{
}
#endregion
#region TideModule
// Place your methods here
public void TideUpdate ()
{
ulong timeStamp;
double cyclePos; //cycles from 0.0000000001 to 0.999999999999
double cycleRadians;
double tideRange;
double tideMiddle;
string tideLevelMsg;
if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready) {
return;
}
timeStamp = (ulong) (DateTime.Now.Ticks);
cyclePos = (double)(timeStamp % (m_cycleTime * TICKS_PER_SECOND)) / (m_cycleTime * TICKS_PER_SECOND);
cycleRadians = cyclePos * Math.PI * 2;
if (cyclePos < 0.5) m_tideDirection = false; else m_tideDirection = true;
if (m_tideDirection != m_lastTideDirection)
{ //if the tide changes re-calculate the tide times
if (cyclePos < 0.5)
{ // tide just changed to be high->low
m_lowTideTime = DateTime.Now.AddSeconds((double)(m_cycleTime * (0.5 - cyclePos)));
m_highTideTime = m_lowTideTime.AddSeconds((double)(m_cycleTime / 2));
m_tideAnnounceMsg = "High Tide";
}
else
{ //tide just changed to be low->high
m_highTideTime = DateTime.Now.AddSeconds((double)(m_cycleTime * (1.0 - cyclePos)));
m_lowTideTime = m_highTideTime.AddSeconds((double)(m_cycleTime / 2));
m_tideAnnounceMsg = "Low Tide";
}
m_lastTideDirection = m_tideDirection;
}
tideRange = (double) (m_highTide - m_lowTide) / 2;
tideMiddle = (double) m_lowTide + tideRange;
m_tideLevel = (float) (Math.Cos(cycleRadians) * tideRange + tideMiddle);
tideLevelMsg = "Current Server Time: " + DateTime.Now.ToString("T") + "\n";
tideLevelMsg += "Current Tide Level: " + m_tideLevel.ToString() + "\n";
tideLevelMsg += "Low Tide Time: " + m_lowTideTime.ToString("T") + "\n";
tideLevelMsg += "Low Tide Level: " + m_lowTide.ToString() + "\n";
tideLevelMsg += "High Tide Time: " + m_highTideTime.ToString("T") + "\n";
tideLevelMsg += "High Tide Level: " + m_highTide.ToString() + "\n";
tideLevelMsg += "Tide Direction: " + ((m_tideDirection) ? "Coming In" : "Going Out") + "\n";
tideLevelMsg += "Cycle Position: " + cyclePos.ToString() + "\n";
if (m_tideAnnounceMsg != "")
{
if (m_tideAnnounceCounter++ > m_tideAnnounceCount)
{
m_tideAnnounceCounter = 0;
m_tideAnnounceMsg = "";
}
else
{
tideLevelMsg += "Tide Warning: " + m_tideAnnounceMsg + "\n";
}
}
if (m_tideInfoDebug) m_log.InfoFormat("[{0}]: Sea Level currently at {1}m in Region: {2}", m_name, m_tideLevel, m_scene.RegionInfo.RegionName);
if (m_tideInfoBroadcast && m_tideDirection)
{
m_scene.SimChatBroadcast(Utils.StringToBytes(tideLevelMsg), ChatTypeEnum.Region, m_tideInfoChannel, m_shoutPos, "TIDE", UUID.Zero, false);
m_scene.SimChatBroadcast(Utils.StringToBytes(m_tideLevel.ToString()), ChatTypeEnum.Region, m_tideLevelChannel, m_shoutPos, "TIDE", UUID.Zero, false);
}
if (m_tideInfoDebug) m_log.InfoFormat("[{0}]: Updating Region: {1}", m_name, m_scene.RegionInfo.RegionName);
m_scene.RegionInfo.RegionSettings.WaterHeight = m_tideLevel;
m_scene.EventManager.TriggerRequestChangeWaterHeight(m_tideLevel);
m_scene.EventManager.TriggerTerrainTick();
if (m_tideInfoBroadcast && !m_tideDirection)
{
m_scene.SimChatBroadcast(Utils.StringToBytes(tideLevelMsg), ChatTypeEnum.Region, m_tideInfoChannel, m_shoutPos, "TIDE", UUID.Zero, false);
m_scene.SimChatBroadcast(Utils.StringToBytes(m_tideLevel.ToString()), ChatTypeEnum.Region, m_tideLevelChannel, m_shoutPos, "TIDE", UUID.Zero, false);
}
}
private void InterfaceMultiplyTerrain(Object[] args)
{
int x, y;
for (x = 0; x < m_channel.Width; x++)
for (y = 0; y < m_channel.Height; y++)
m_channel[x, y] *= (double)args[0];
}
public void UpdateTerrainWithTide()
{
float terrain_scale = 0.75 * m_channel.Height;
float terrain_scale2 = 0.95 * m_channel.Height;
while (tideDirection == true)
{
if (m_tideLevel > terrain_scale && m_tideLevel < terrain_scale2)
{
InterfaceMultiplyTerrain(0.95);
}
}
}
#endregion
}
}

Automatic Picture Slider C#

I would like that when the form loads and/or starts my picture slide will start automatically.I tried to put the path of where the folder is located but it keeps giving an error. When I use it a dialog box it works. I am trying to bypass the dialog box so it starts automatically.
public partial class Form1 : Form
{
private string[] folderFile = null;
private int selected = 0;
private int end = 0;
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
// The folder is pre created
string path1 = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Pictures";
public Form1()
{
InitializeComponent();
//This does not work when the form starts up.
if (!Directory.Exists(path1))
{
string[] part1 = null, part2 = null, part3 = null;
part1 = Directory.GetFiles(path1, "*.jpg");
part2 = Directory.GetFiles(path1, "*.jpeg");
part3 = Directory.GetFiles(path1, "*.bmp");
folderFile = new string[part1.Length + part2.Length + part3.Length];
Array.Copy(part1, 0, folderFile, 0, part1.Length);
Array.Copy(part2, 0, folderFile, part1.Length, part2.Length);
Array.Copy(part3, 0, folderFile, part1.Length + part2.Length, part3.Length);
selected = 0;
//begin = 0;
end = folderFile.Length;
showImage(folderFile[selected]);
// 5 to 10 second intervals
//timer1.Enabled = true;
}
else
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
nextImage();
}
private void btnFolder_Click(object sender, EventArgs e)
{
//Original
//This works!!
//while (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
//{
// string[] part1 = null, part2 = null, part3 = null;
// part1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg");
// part2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpeg");
// part3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.bmp");
// folderFile = new string[part1.Length + part2.Length + part3.Length];
// Array.Copy(part1, 0, folderFile, 0, part1.Length);
// Array.Copy(part2, 0, folderFile, part1.Length, part2.Length);
// Array.Copy(part3, 0, folderFile, part1.Length + part2.Length, part3.Length);
// selected = 0;
// //begin = 0;
// end = folderFile.Length;
// showImage(folderFile[selected]);
// //btnPrev.Enabled = true;
// //btnNext.Enabled = true;
// //btnStartSlide.Enabled = true;
//}
}
private void showImage(string path)
{
Image imgtemp = Image.FromFile(path);
//pictureBox1.Width = imgtemp.Width / 2;
//pictureBox1.Height = imgtemp.Height / 2;
//pictureBox1.Image = imgtemp;
panel1.BackgroundImage = imgtemp;
}
private void prevImage()
{
if (selected == 0)
{
selected = folderFile.Length - 1;
showImage(folderFile[selected]);
}
else
{
selected = selected - 1;
showImage(folderFile[selected]);
}
}
private void nextImage()
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1;
showImage(folderFile[selected]);
}
}
private void btnPreviews_Click(object sender, EventArgs e)
{
prevImage();
}
private void btnNext_Click(object sender, EventArgs e)
{
nextImage();
}
private void btnStart_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
timer1.Enabled = false;
btnStart.Text = "<< START >>";
}
else
{
timer1.Enabled = true;
btnStart.Text = "<< STOP >>";
}
}
}
}
Try
string path1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\Sample_Pictures";
or
string path1 = Environment.GetFolderPath(Environment.SpecialFolder.CommonPictures) + "\\Sample_Pictures";
Or use
string publicDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
var directory = new DirectoryInfo(publicDesktopPath);
string path1 = directory.Parent.FullName + "\\Pictures\\Sample_Pictures";
and fix your conditional
if (!Directory.Exists(path1)) {
to
if (Directory.Exists(path1)) {
so that you don't try operations on an non-existent directory.
To get it to cycle through your pictures, you could use a System.Timers.Timer:
In your Form1 class
private static Timer timer;
Declare the timer in your constructor:
timer = new System.Timers.Timer(5000); // change interval in milliseconds
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
Create the OnTimedEvent method in your Form1 class:
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
// Do what you want every time the timer elapses that interval
nextImage();
}

Label's position is different in xp and 7

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.

Categories

Resources