ObjectListView show icons - c#

Trying to put icons in ObjectListview, here's my piece of code where icon should have been put:
objectListView1.SmallImageList = imageList1;
deleteColumn.IsEditable = true;
deleteColumn.ImageGetter = delegate
{
return 0;
};
deleteColumn.AspectGetter = delegate
{
return "Delete";
};
imageList1 already have an image, this code should have put an icon next to "Delete", but it did not appear at all, looked through cookbooks and Google and I still have no idea. Can anyone help me?
this is the full form code in case needed:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
objectListView1.AllowDrop = true;
objectListView1.DragEnter += new DragEventHandler(objectListView1_DragEnter);
objectListView1.DragDrop += new DragEventHandler(objectListView1_DragDrop);
objectListView1.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.SingleClick;
objectListView1.CellEditStarting += deleteItems;
objectListView1.SmallImageList = imageList1;
deleteColumn.IsEditable = true;
deleteColumn.ImageGetter = delegate
{
return 0;
};
deleteColumn.AspectGetter = delegate
{
return "Delete";
};
}
private void objectListView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void objectListView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
{
string[] droppedFiles = (string[]) e.Data.GetData(DataFormats.FileDrop);
foreach (string path in droppedFiles)
{
if (File.Exists(path))
{
FileObject fo = new FileObject(path, "added later");
objectListView1.AddObject(fo);
}
}
}
}
private void deleteItems(object sender, BrightIdeasSoftware.CellEditEventArgs e)
{
if(e.Column == deleteColumn)
{
e.Cancel = true;
objectListView1.RemoveObject(e.RowObject);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}

In order for images to appear next to the text in a column, you must:
Connect the ObjectListView to an ImageList (using the SmallImageList property);
Install an ImageGetter delegate for the column that must show the images;
Make sure that there are actually images in the ImageList.
With this done, images will appear (I just tested this).
There is one catch, though. From your question, I suspect that the "Delete" column may not be the first column in the ObjectListView. The above steps only allow you to show an image in the very first column. For subsequent columns, you will have to set the ShowImagesOnSubItems property to True. Could that be it?

Related

Picture box not displaying Emgu.cv.mat.toBitmap image

Was following a tutorial on YouTube and tried to get my program to display the live video feed from my webcam into the forms picture box but for some reason the webcam comes on but the picture box isn't displaying anything
I have tried checking if the Mat class was returning null.
but it isn't this is my code
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 Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.UI;
namespace FaceRecognitionAttandanceSystem
{
public partial class StudentAdd : Form
{
public string fileName { get; set; }
VideoCapture capture;
public StudentAdd()
{
InitializeComponent();
}
//Open Folder
private void metroButton3_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "JPEG|*.jpg", ValidateNames = true, Multiselect = false };
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//open file explorer
fileName = openFileDialog.FileName;
//pick image from file
Image img = Image.FromFile(fileName);
//Rotates Image by 90degrees
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox2.Image = img;
}
}
}
//Capture Image
private void metroButton4_Click(object sender, EventArgs e)
{
//If capture is empty start new video capture
if(capture == null)
{
capture = new Emgu.CV.VideoCapture(0);
}
capture.ImageGrabbed += Capture_ImageGrabbed;
capture.Start();
}
private void Capture_ImageGrabbed(object sender, EventArgs e)
{
try
{
Mat mat = new Mat();
if(mat == null)
{
Console.WriteLine("Here you Go");
}
capture.Retrieve(mat);
pictureBox1.Image = mat.ToImage<Bgr, Byte>().ToBitmap<Bgr, Byte>();
}
catch(Exception)
{
}
}
private void metroButton5_Click(object sender, EventArgs e)
{
}
}
}
The problem is very likely that the Capture_ImageGrabbed event is raised on a background thread. And you can only update the UI on the UI thread. You can place a break point in the event-handler and check the thread-debug window to confirm. To fix this you need to move execution to the UI thread. Try:
capture.Retrieve(mat);
var bitmap = mat.ToImage<Bgr, Byte>().ToBitmap<Bgr, Byte>();
pictureBox1.Invoke(() => pictureBox1.Image = bitmap );
You might need to write Invoke((Action)(() => pictureBox1.Image = bitmap) ), since I think there is some issues with the overload resolution of lambdas with the invoke-method.

Writing to CSV File in C#

I am creating a clock for clocking into a business. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
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 System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
String Code;
String Name;
String InOut;
Boolean Luke = true;
String csvPath = "C:/users/luke/documents/C#/csvProject.csv";
StringBuilder Header = new StringBuilder();
StringBuilder csvData = new StringBuilder();
public Form1()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
TopMost = true;
Header.AppendLine("Timestamp, Name");
File.AppendAllText(csvPath, Header.ToString());
textBox1.Font = new Font("Arial", 30, FontStyle.Bold);
}
private void button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
Code = Code + button.Text;
textBox1.Text = Code;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
FormBorderStyle = FormBorderStyle.Sizable;
WindowState = FormWindowState.Normal;
TopMost = false;
}
}
private void button13_Click(object sender, EventArgs e)
{
//clear
Code = null;
textBox1.Text = Code;
}
private void button10_Click(object sender, EventArgs e)
{
//in or out
DateTime timeStamp = DateTime.Now;
if (Code == "123")
{
Name = "Luke";
}
Button button = (Button)sender;
csvData.AppendLine(timeStamp + "," + Name + "," + button.Text);
File.AppendAllText(csvPath, csvData.ToString());
Code = null;
textBox1.Text = Code;
}
private void button14_Click(object sender, EventArgs e)
{
}
}
}
My layout consists of a number pad, in button, and out button. When the user presses the in button after they enter their code, the program should write in the CSV file: Timestamp, Name, In. When I tested the code by clocking in, the program writes one row correctly. When I clock in and then clock out, it creates two rows of me clocking in and one row of me clocking out. I was wondering if anyone could help me find what is going wrong in the code. Thanks.
You need to empty csvData after writing it to the file.

WebBrowser Control LoadCompleted

I'm using Web browser in my form which navigates to multiple pages. I want to take screenshot of Last page once loaded completely. I've coded taking screen shot inside the webBrowser1_DocumentCompleted. However it is taking screenshot before page getting loaded. I'm confused where I can take screenshot. I found LoadCompleted event in google but not sure how to use. Please help me out.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing.Imaging;
namespace CC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
string url = "http://www.lll.com";
webBrowser1.Navigate(new Uri(url));
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
catch (Exception ex)
{
}
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string AbsoluteURL = e.Url.AbsolutePath.ToString();
int count = 0;
switch (AbsoluteURL)
{
case "Page1":
var loginControl = webBrowser1.Document.GetElementById("user");
var passwordControl = webBrowser1.Document.GetElementById("password");
var btn = webBrowser1.Document.GetElementById("Submit");
if (loginControl != null)
loginControl.SetAttribute("value", "XXX");
if (passwordControl != null)
passwordControl.SetAttribute("value", "YYY");
var elems = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
if (elem.GetAttribute("tabindex") == "3")
{
elem.InvokeMember("click");
}
}
break;
case"Page2": // THIS IS NOT WORKING. TAKING SCREEN SHOT BEFORE PAGE GETTING LOADED FULLY. NEED HELP HERE
using (Bitmap bitmap = new Bitmap(webBrowser1.Width, webBrowser1.Height, PixelFormat.Format24bppRgb))
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(
PointToScreen(webBrowser1.Location),
new Point(0, 0),
webBrowser1.Size);
bitmap.Save(#"C:\123.bmp");
}
break;
default:
Console.WriteLine("Better try again");
break;
}
}
}
}
}
Try this one.
protected void Capture(object sender, EventArgs e)
{
string url = "www.google.com";
Thread thread = new Thread(delegate()
{
using (WebBrowser browser = new WebBrowser())
{
browser.ScrollBarsEnabled = false;
browser.AllowNavigation = true;
browser.Navigate(url);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = sender as WebBrowser;
//do what do you want
}
In my experience, navigation and document loading are distinct from having the document be actually rendered. I would look at ReadyState https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowserreadystate%28v=vs.110%29.aspx to determine of the document is actually rendered and not just loaded.

How can i check for text identical in textBox while typing inside the textBox?

I have this Form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GatherLinks
{
public partial class ChangeLink : Form
{
public ChangeLink()
{
InitializeComponent();
}
public string getText()
{
return textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
DialogResult = DialogResult.OK;
}
else
{
}
}
private void ChangeLink_Load(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
}
}
And this code in Form1:
public void KeysValuesUpdate()
{
DialogResult dr = DialogResult.None;
using (var w = new StreamWriter(keywords_path_file))
{
crawlLocaly1 = new CrawlLocaly(this);
crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
if (FormIsClosing != true)
{
dr = crawlLocaly1.ShowDialog(this);
}
if (dr == DialogResult.OK)
{
if (LocalyKeyWords.ContainsKey(mainUrl))
{
LocalyKeyWords[mainUrl].Clear();
LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
}
else
{
LocalyKeyWords[mainUrl] = new List<string>();
LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
}
Write(w);
ClearListBox();
}
if (dr == DialogResult.Cancel)
{
Write(w);
}
if (dr == DialogResult.None)
{
Write(w);
}
}
}
This KeysValuesUpdate() function is called here:
private void button2_Click(object sender, EventArgs e)
{
cl = new ChangeLink();
cl.StartPosition = FormStartPosition.CenterParent;
DialogResult dr = cl.ShowDialog(this);
if (dr == DialogResult.Cancel)
{
cl.Close();
}
else if (dr == DialogResult.OK)
{
label4.Text = cl.getText();
mainUrl = cl.getText();
if (!LocalyKeyWords.ContainsKey(mainUrl))
{
newUrl = true;
KeysValuesUpdate();
}
else
{
newUrl = false;
KeysValuesUpdate();
}
OptionsDB.set_changeWebSite(cl.getText());
cl.Close();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
When I click the button2 it's opening the new Form with a textbox and then inside I can type text.
Then I checking if the text inside already exist then newUrl is false or true.
Then when I click OK the OK button in the new Form then it's checking if the text I typed Contain/exist already or not.
I want that when the user type something in the textbox while he is typing if it's Contain/Exist the key then color the text in the textbox in Red one the user is keep typing and the text is not Contain/EXist color it back to Black but each time if the text in the textbox Contain/Exist already color it in Red and only if it's match case not if the text is inside other text:
This is in black:
For example : Danny hello all
But if I type in the textbox only: hello
Then the word hello will be in Red then if I kept typing after the hello then all the text in the textbox is Black if I delete the text and kept only the word hello then it will be Red again.
And that should be according to the code above and in realtime when im typing text in the textbox.
The new Form again with updated code with the textBox1 text changed event:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GatherLinks
{
public partial class ChangeLink : Form
{
Form1 f1;
public ChangeLink(Form1 f)
{
InitializeComponent();
f1 = f;
}
public string getText()
{
return textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
DialogResult = DialogResult.OK;
}
else
{
}
}
private void ChangeLink_Load(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (f1.mainUrl.Contains(textBox1.Text))
{
textBox1.ForeColor = Color.Red;
}
else
textBox1.ForeColor = Color.Black;
}
}
}
private void textBox_TextChanged(object sender, EventArgs e)
{
if (Regex.IsMatch(yourtext, #"\b" + textBox.Text + #"\b"))
{
textBox.ForeColor = Color.Red;
}
else
textBox.ForeColor = Color.Black;
}
Place your data containing variable name at the place of yourtext.
I have edited the answer. It is perfectly matching the whole words as you asked to do. To use Regex class, include System.Text.RegularExpressions namesapce.
You can implement textBox1 TextChanged event handler simply by defining a method
private void textBox1_TextChanged(object sender, EventArgs e)
{
var textBox = sender as TextBox;
String text = textBox.Text;
if (SomeCheck(text))
{
textBox.ForeColor = Color.Red;
}
else
{
textBox.ForeColor = Color.Black;
}
}
and assigning method textBox1_TextChanged to OnTextChanged property of textBox

How can i load item from a listBox as file and show the file content?

I have this Code in Form1. Im doing a search for xml files. When i find them im using listBox1 selected index changed event and i want to do that when i select item in the lixtBox it will consider it as a file will parse it content and show me the parsed content.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.IO;
using System.Collections;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DirectoryInfo dirinf = new DirectoryInfo(#"C:\");
List<FileSystemInfo> fsi = new List<FileSystemInfo>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
}
private void ParseAndDisplayXml(string filename)
{
XDocument document = XDocument.Load(filename);
var list = document.Root.Elements("Message")
.Select(
e => new
{
Date = e.Attribute("Date").Value.ToString(),
Time = e.Attribute("Time").Value.ToString(),
Text = e.Element("Text").Value.ToString()
}
);
string result="";
foreach (var item in list)
{
result += string.Format("Date--{0},Time--{1},Text--{2}", item.Date, item.Time, item.Text + Environment.NewLine);
}
}
public void Search(string strExtension,
DirectoryInfo di,
List<FileSystemInfo> pResult)
{
try
{
foreach (FileInfo fi in di.GetFiles())
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => label2.Text = fi.Name));
}
if (fi.Name == "MessageLog.xsl")
{
foreach (FileInfo fii in di.GetFiles())
{
if (fii.Extension == strExtension)
pResult.Add(fii);
}
if (InvokeRequired)
{
BeginInvoke(new Action(() => label4.Text = pResult.Count.ToString() + Environment.NewLine));
}
}
}
foreach (DirectoryInfo diChild in di.GetDirectories())
Search(strExtension, diChild, pResult);
}
catch (Exception e)
{
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Search(".xml", dirinf, fsi);
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
for (int i = 0; i < fsi.Count; i++)
{
listBox1.Items.Add(fsi[i].Name + Environment.NewLine);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label2.Text = listBox1.SelectedItem.ToString();
}
}
}
Im starting the search from C:\
Then when the search so over completed im adding the items it found to the listBox1.
For example now in my listBox1 i have 4 files:
danny.xml
adi.xml
sharon.xml
yoval.xml
In the selectedindexchanged i added option so the user can move between the items.
Now what i want to do is when the user select some index for example index [1] in the listBox and only if he clicked enter with the keyboard or clicked with the mouse left click it will call/use the function: ParseAndDisplayXML.
Then it will parse the selected index wich need to be translated to a file so in the backgroundWorker1_RunWorkerCompleted event i madding the files to the listBox as items but only with the names of the files. If i did .FullName instead .Name it was adding the files names with the directories too.
So i need somehow to get the FullName of the files in the completed event i think then when selecting one of the FullName items to parse it and display it in the listBox.
The parse function should take the specific content from the xml files and it worked i checked this function before alone.
The problem is how do i make that the user will select the index by click/key enter and how to parse and display it ?
When you add something to a listbox.
It expects an object, and sets the text to object.ToString()
e.g.
MyListBox.Add(100);
Would box 100 and display "100"
Couldn't find if FileSystemInfo's ToString() method has been overridden but first thing to try would be
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
// newline is unnecesary and you should be using foreach
foreach(FileSystemInfo f in fsi)
{
listBox1.Items.Add(f);
}
}
// display full name of file
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label2.Text = ((FileSystemInfo)listBox1.SelectedItem).Fullname;
}
If FileSystemInfo.ToString() doesn't return Name, there are a few ways to deal with that.
If you don't want to hold on to the FileSystemInfo instances, we can deal with that too.

Categories

Resources