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.
Related
In the designer in the listBox1 properties i set the DrawMode to OwnerDrawFixed
Then added this class for the coloring :
public class MyListBoxItem
{
public MyListBoxItem(Color c, string m)
{
ItemColor = c;
Message = m;
}
public Color ItemColor { get; set; }
public string Message { get; set; }
}
and added event of the DrawItem :
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
if (item != null)
{
e.Graphics.DrawString( // Draw the appropriate text in the ListBox
item.Message, // The message linked to the item
listBox1.Font, // Take the font from the listbox
new SolidBrush(item.ItemColor), // Set the color
0, // X pixel coordinate
e.Index * listBox1.ItemHeight // Y pixel coordinate. Multiply the index by the ItemHeight defined in the listbox.
);
}
else
{
// The item isn't a MyListBoxItem, do something about it
}
}
then i'm trying to add some items just for testing in the constructor :
each item should be in another color :
listBox1.Items.Add(new MyListBoxItem(Colors.Green, "Validated data successfully"));
listBox1.Items.Add(new MyListBoxItem(Colors.Red, "Failed to validate data"));
but getting exception on the first listBox1.Items.Add line :
System.ArgumentException: 'Items collection cannot be modified when the DataSource property is set.'
this is the full code :
using Newtonsoft.Json;
using Ookii.Dialogs.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
namespace Image_Crop
{
public partial class Form1 : Form
{
Rectangle rect;
int pixelsCounter = 0;
Color SelectedColor = Color.LightGreen;
List<DrawingRectangle> DrawingRects = new List<DrawingRectangle>();
Bitmap rectImage;
int saveRectanglesCounter = 1;
bool drawBorder = true;
bool clearRectangles = true;
bool saveRectangles = true;
string rectangleName;
Dictionary<string, string> FileList = new Dictionary<string, string>();
string selectedPath;
int x, y;
private bool crop = false;
public Form1()
{
InitializeComponent();
textBox1.Text = Properties.Settings.Default.ImageToCropFolder;
textBox2.Text = Properties.Settings.Default.CroppedImagesFolder;
selectedPath = textBox2.Text;
if (textBox1.Text != "")
{
Bitmap bmp = new Bitmap(Image.FromFile(textBox1.Text),
pictureBox2.Width, pictureBox2.Height);
pictureBox2.Image = bmp;
}
checkBoxDrawBorder.Checked = true;
checkBoxClearRectangles.Checked = true;
checkBoxSaveRectangles.Checked = true;
if (selectedPath != "" && selectedPath != null)
{
if (System.IO.File.Exists(Path.Combine(selectedPath, "rectangles.txt")))
{
string g = System.IO.File.ReadAllText(Path.Combine(selectedPath, "rectangles.txt"));
g = g.Remove(0, 32);
FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
listBox1.DataSource = FileList.Keys.ToList();
label2.Text = listBox1.Items.Count.ToString();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
else
{
label2.Text = "0";
}
}
else
{
label2.Text = "0";
}
if ((selectedPath != "" && selectedPath != null) && textBox1.Text != "")
{
crop = true;
}
else
{
crop = false;
}
listBox1.Items.Add(new MyListBoxItem(Color.Green, "Validated data successfully"));
listBox1.Items.Add(new MyListBoxItem(Color.Red, "Failed to validate data"));
}
public class DrawingRectangle
{
public Rectangle Rect => new Rectangle(Location, Size);
public Size Size { get; set; }
public Point Location { get; set; }
public Control Owner { get; set; }
public Point StartPosition { get; set; }
public Color DrawingcColor { get; set; } = Color.LightGreen;
public float PenSize { get; set; } = 3f;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left || crop == false) return;
x = 0;
y = 0;
if (pictureBox2.Image != null && selectedPath != null)
{
if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
{
DrawingRects.Add(new DrawingRectangle()
{
Location = e.Location,
Size = Size.Empty,
StartPosition = e.Location,
Owner = (Control)sender,
DrawingcColor = SelectedColor
});
}
}
}
private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
{
int X = e.X;
int Y = e.Y;
if (e.Button != MouseButtons.Left || crop == false) return;
if ((X >= 0 && X <= pictureBox2.Width) && (Y >= 0 && Y <= pictureBox2.Height))
{
if (pictureBox2.Image != null && selectedPath != null && DrawingRects.Count > 0)
{
if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
{
x = e.X;
y = e.Y;
var dr = DrawingRects[DrawingRects.Count - 1];
if (e.Y < dr.StartPosition.Y) { dr.Location = new Point(dr.Rect.Location.X, e.Y); }
if (e.X < dr.StartPosition.X) { dr.Location = new Point(e.X, dr.Rect.Location.Y); }
dr.Size = new Size(Math.Abs(dr.StartPosition.X - e.X), Math.Abs(dr.StartPosition.Y - e.Y));
pictureBox2.Invalidate();
}
}
}
}
int count = 0;
private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left || crop == false) return;
if (DrawingRects.Count > 0 && pictureBox2.Image != null && selectedPath != "")
{
if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
{
var dr = DrawingRects.Last();
if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
{
rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);
if (saveRectangles)
{
count++;
rectangleName = GetNextName(Path.Combine(selectedPath, "Rectangle"), ".bmp");
FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
string json = JsonConvert.SerializeObject(
FileList,
Formatting.Indented
);
using (StreamWriter sw = new StreamWriter(Path.Combine(selectedPath, "rectangles.txt"), false))
{
sw.WriteLine("Total number of rectangles: " + count + Environment.NewLine);
sw.Write(json);
sw.Close();
}
rectImage.Save(rectangleName);
saveRectanglesCounter++;
}
else
{
var stream = ToMemoryStream(rectImage);
var image = System.Drawing.Image.FromStream(stream);
pictureBox1.Image = image;
}
pixelsCounter = rect.Width * rect.Height;
pictureBox1.Invalidate();
listBox1.DataSource = FileList.Keys.ToList();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
pictureBox2.Focus();
Graphics g = Graphics.FromImage(this.pictureBox1.Image);
g.Clear(this.pictureBox1.BackColor);
}
}
else
{
if (clearRectangles)
{
DrawingRects.Clear();
pictureBox2.Invalidate();
}
x = 0;
y = 0;
}
}
}
public class MyListBoxItem
{
public MyListBoxItem(Color c, string m)
{
ItemColor = c;
Message = m;
}
public Color ItemColor { get; set; }
public string Message { get; set; }
}
public MemoryStream ToMemoryStream(Bitmap b)
{
MemoryStream ms = new MemoryStream();
b.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms;
}
string GetNextName(string baseName, string extension)
{
int counter = 1;
string nextName = baseName + counter + extension;
while (System.IO.File.Exists(nextName))
{
counter++;
nextName = baseName + counter + extension;
}
return nextName;
}
private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
if (drawBorder)
{
ControlPaint.DrawBorder(e.Graphics, pictureBox2.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
}
if (pictureBox2.Image != null && selectedPath != null && DrawingRects.Count > 0)
{
DrawShapes(e.Graphics);
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (drawBorder)
{
ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
}
if (rectImage != null && DrawingRects.Count > 0)
{
var dr = DrawingRects.Last();
e.Graphics.DrawImage(rectImage, dr.Rect);
if (clearRectangles)
{
DrawingRects.Clear();
pictureBox2.Invalidate();
}
}
}
private void DrawShapes(Graphics g)
{
if (DrawingRects.Count == 0) return;
g.SmoothingMode = SmoothingMode.AntiAlias;
foreach (var dr in DrawingRects)
{
if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
{
using (Pen pen = new Pen(dr.DrawingcColor, dr.PenSize))
{
g.DrawRectangle(pen, dr.Rect);
};
}
}
}
public Bitmap cropAtRect(Bitmap b, Rectangle r)
{
Bitmap nb = new Bitmap(r.Width, r.Height);
using (Graphics g = Graphics.FromImage(nb))
{
g.DrawImage(b, -r.X, -r.Y);
return nb;
}
}
private void checkBoxDrawBorder_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxDrawBorder.Checked)
{
drawBorder = true;
}
else
{
drawBorder = false;
}
pictureBox1.Invalidate();
pictureBox2.Invalidate();
}
private void checkBoxClearRectangles_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxClearRectangles.Checked)
{
clearRectangles = true;
}
else
{
clearRectangles = false;
}
pictureBox2.Invalidate();
}
private void checkBoxSaveRectangles_CheckedChanged(object sender, EventArgs e)
{
if(checkBoxSaveRectangles.Checked)
{
saveRectangles = true;
}
else
{
saveRectangles = false;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = ((ListBox)sender).SelectedItem;
var val = FileList[(string)item];
if (File.Exists(val))
{
pictureBox1.Image = System.Drawing.Image.FromFile(val);
}
}
private void button1_Click(object sender, EventArgs e)
{
VistaOpenFileDialog dialog = new VistaOpenFileDialog();
{
dialog.Filter = "Images (*.jpg, *.bmp, *.gif)|*.jpg;*.bmp;*.gif";
};
if (dialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dialog.FileName;
Properties.Settings.Default.ImageToCropFolder = dialog.FileName;
Properties.Settings.Default.Save();
Bitmap bmp = new Bitmap(Image.FromFile(dialog.FileName),
pictureBox2.Width, pictureBox2.Height);
pictureBox2.Image = bmp;
if(textBox1.Text != "" && textBox2.Text != "")
{
crop = true;
}
}
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
if (item != null)
{
e.Graphics.DrawString( // Draw the appropriate text in the ListBox
item.Message, // The message linked to the item
listBox1.Font, // Take the font from the listbox
new SolidBrush(item.ItemColor), // Set the color
0, // X pixel coordinate
e.Index * listBox1.ItemHeight // Y pixel coordinate. Multiply the index by the ItemHeight defined in the listbox.
);
}
else
{
// The item isn't a MyListBoxItem, do something about it
}
}
private void button2_Click(object sender, EventArgs e)
{
VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
textBox2.Text = dialog.SelectedPath;
selectedPath = dialog.SelectedPath;
Properties.Settings.Default.CroppedImagesFolder = selectedPath;
Properties.Settings.Default.Save();
if (textBox1.Text != "" && textBox2.Text != "")
{
crop = true;
}
}
}
}
}
Your question is How to color items in listBox in different colors? and the "Y" of what might be considered an X-Y Problem is that you get an exception when you try to Add an item inline. After carefully reading your code, something that would make a big difference would be using the MyListBoxItem type consistently in both in your DataSource and your Json serialization and deserialization, and then appending the data source when you wish to Add an item inline.
Datasource
BindingList<MyListBoxItem> MyItems { get; } = new BindingList<MyListBoxItem>();
Example of MyItems in Json-Serialized form in the disk file
[
{
"ItemColor": "Blue",
"Message": "Blue Item"
},
{
"ItemColor": "Green",
"Message": "Green Item"
},
{
"ItemColor": "Red",
"Message": "Red Item"
}
]
Where:
public class MyListBoxItem
{
public Color ItemColor { get; set; }
public string Message { get; set; }
}
Main Form initialization for listBox1 drawing code
public partial class MainForm : Form
{
public MainForm() => InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
listBox1.DisplayMember = nameof(MyListBoxItem.Message);
listBox1.DataSource = MyItems;
listBox1.DrawItem += onDrawItem;
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
listBox1.SelectedIndexChanged += (sender, e) => listBox1.Refresh();
// Tests
buttonTest.Click += onButtonTest;
buttonReadJson.Click += onButtonReadJson;
}
private void onDrawItem(object sender, DrawItemEventArgs e)
{
if((e.Index == -1) || (e.Index >= MyItems.Count))
{
e.DrawBackground();
}
else
{
var myItem = MyItems[e.Index];
if (listBox1.SelectedItems.Contains(myItem))
{
using (var backgroundBrush = new SolidBrush(myItem.ItemColor))
{
e.Graphics.FillRectangle(backgroundBrush, e.Bounds);
}
using (var textBrush = new SolidBrush(Color.White))
{
e.Graphics.DrawString(myItem.Message, listBox1.Font, textBrush, e.Bounds);
}
}
else
{
using (var backgroundBrush = new SolidBrush(SystemColors.Window))
{
e.Graphics.FillRectangle(backgroundBrush, e.Bounds);
}
using (var textBrush = new SolidBrush(myItem.ItemColor))
{
e.Graphics.DrawString(myItem.Message, listBox1.Font, textBrush, e.Bounds);
}
}
}
}
BindingList<MyListBoxItem> MyItems { get; } = new BindingList<MyListBoxItem>();
.
.
.
}
Example of adding items
private void onButtonTest(object sender, EventArgs e)
{
MyItems.Clear();
MyItems.Add(new MyListBoxItem
{
Message = "Validated data successfully",
ItemColor = Color.Green,
});
MyItems.Add(new MyListBoxItem
{
Message = "Failed to validate data",
ItemColor = Color.Red,
});
}
Example of deserializing file
private void onButtonReadJson(object sender, EventArgs e)
{
MyItems.Clear();
foreach (
var myItem
in JsonConvert.DeserializeObject<List<MyListBoxItem>>(mockFileContents))
{
MyItems.Add(myItem);
}
}
const string mockFileContents =
#"[
{
""ItemColor"": ""Blue"",
""Message"": ""Blue Item""
},
{
""ItemColor"": ""Green"",
""Message"": ""Green Item""
},
{
""ItemColor"": ""Red"",
""Message"": ""Red Item""
}
]";
I am new in C# and trying to create zedgraph of lessor sensor.
First I create a global variable and write code for graph. My graph is working but after reached to the point of 100 of x axis it will overlap to old line. z1.GraphPane.CurveList.Clear(); command is not working. I tried listPointsOne.clear(); command also but that clear the line and doesn't show anything on graph. Please help me out with this.
My code is below :
string DatafromCOM;
double[] x = new double[100];
double[] y = new double[100];
int i;
PointPairList listPointsOne = new PointPairList();
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
while (serialPort1.BytesToRead > 0)
{
DatafromCOM = serialPort1.ReadLine();
double iData;
var ok = double.TryParse(txtKQ.Text, out iData);
if (DatafromCOM.Trim() != "" && ok)
{
i= (i + 1) % 100;
x[i] = i;
y[i] = iData;
listPointsOne.Add(i,iData);
}
}
}
catch { }
}
private void timer1_Tick(object sender, EventArgs e)
{
z1.GraphPane.CurveList.Clear();
z1.GraphPane.AddCurve(null, listPointsOne, Color.Red, SymbolType.None);
z1.AxisChange();
z1.Invalidate();
}
You should clear the curvlist
string DatafromCOM;
double[] x = new double[100];
double[] y = new double[100];
int i;
PointPairList listPointsOne = new PointPairList();
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
while (serialPort1.BytesToRead > 0)
{
DatafromCOM = serialPort1.ReadLine();
double iData;
var ok = double.TryParse(txtKQ.Text, out iData);
if (DatafromCOM.Trim() != "" && ok)
{
i= (i + 1) % 100;
x[i] = i;
y[i] = iData;
listPointsOne.Add(i,iData);
}
z1.GraphPane.CurveList.Clear(); // Change here
}
}
catch { }
}
private void timer1_Tick(object sender, EventArgs e)
{
z1.GraphPane.AddCurve(null, listPointsOne, Color.Red, SymbolType.None);
z1.AxisChange();
z1.Invalidate();
}
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.
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.
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();
}