I'm trying to implement an application in C# which generates me a QR Code. I've managed to do this, but I don't know how to call CreateQRImage(string inputData) inside the genButton_Click(object sender, EventArgs e).
I inside the windows form I have a textbox and a button, and I think that the function CreateQRImage must be called with the name of the textbox
Here is the code:
private void genButton_Click(object sender, EventArgs e)
{
}
public void CreateQRImage(string inputData)
{
if (inputData.Trim() == String.Empty)
{
System.Windows.Forms.MessageBox.Show("Data must not be empty.");
}
BarcodeWriter qrcoder = new ZXing.BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.QrCode.QrCodeEncodingOptions
{
ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
Height = 250,
Width = 250
}
};
string tempFileName = System.IO.Path.GetTempPath() + inputData + ".png";
Image image;
String data = inputData;
var result = qrcoder.Write(inputData);
image = new Bitmap(result);
image.Save(tempFileName);
System.Diagnostics.Process.Start(tempFileName);
}
This should do the trick:
private void genButton_Click(object sender, EventArgs e)
{
// Assuming your text box name. Also assuming UI disables button until text is entered.
this.CreateQRImage(myTextBox.Text);
}
Related
I have a problem about System.Windows.Forms.PictureBox. I want to show a image on monitor and capture it on the camera. So I use Winform which include a picturebox. The picture box is:
PictureBox pb = new PictureBox();
pb.WaitOnLoad = true;
When I set a bitmap to PictureBox and capture the image from camera,
// Show bmp1
this.image.Image = bmp1;
this.image.Invalidate();
this.image.Refresh();
// Delay 1s
UseTimerToDelay1s();
// Show bmp2
this.image.Image = bmp2;
this.image.Invalidate();
this.image.Refresh();
// Capture
CaptureImageFromCamera();
It only capture the bmp1.
If I add a small delay like this,
this.image.Image = bmp2;
this.image.Invalidate();
this.image.Refresh();
UseTimerToDelay100ms();
CaptureImageFromCamera();
It capture bmp2. The Image set method seem to be a async method. Does any method to confirm the image is set? Thanks.
I'd use the first Paint event after assigning the new Image.
You can give it a try using a very large image url from this site.
The example uses google logo image url. Copy the following code and make sure you assign event handlers to the events:
bool newImageInstalled = true;
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.WaitOnLoad = true;
}
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
if (!newImageInstalled)
{
newImageInstalled = true;
BeginInvoke(new Action(() =>
{
//Capturing the new image
using (var bm = new Bitmap(pictureBox1.ClientSize.Width,
pictureBox1.ClientSize.Height))
{
pictureBox1.DrawToBitmap(bm, pictureBox1.ClientRectangle);
var tempFile = System.IO.Path.GetTempFileName() + ".png";
bm.Save(tempFile, System.Drawing.Imaging.ImageFormat.Png);
System.Diagnostics.Process.Start(tempFile);
}
}));
}
}
private void button1_Click(object sender, EventArgs e)
{
newImageInstalled = false;
pictureBox1.ImageLocation =
"https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
}
private void button2_Click(object sender, EventArgs e)
{
newImageInstalled = false;
pictureBox1.Image = null;
}
I am currently making a podcast client to download episodes. I have got a listView filled with the episodes for a feed and then when you double click on one it places it into a separate 'downloads' lisview which has a 'name' and a 'progress' column.
The problem I am having is trying to individually update each progress while downloading asynchronously. As I am not sure of how to keep track of the progress for each ListViewItem and how to reference it in the downloadProgressChanged function.
private void lvPodDownloads_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lvPodEpisodes.SelectedItems.Count == 1) // Check if an item is selected just to be safe
{
ListViewItem item = (ListViewItem)lvPodEpisodes.SelectedItem;
string[] epInfo = (string[])item.Tag;
txtTitle.Text = epInfo[0];
txtDesc.Text = epInfo[1];
try
{
imgFeedImage.Source = new BitmapImage(new Uri((Environment.CurrentDirectory + "\\..\\..\\feedImages\\" + epInfo[3])));
}
catch (Exception) // If it fails to set the image (Eg. It's non-existent) It will leave it blank
{
imgFeedImage.Source = null;
}
}
}
private void lvPodEpisodes_MouseDoubleClick(object sender, MouseButtonEventArgs e) // Downloading the episode in here
{
if (e.ChangedButton == MouseButton.Left) // Left button was double clicked
{
ListViewItem selected = (ListViewItem)lvPodEpisodes.SelectedItem;
string[] epInfo = (string[])selected.Tag;
Uri downloadUrl = new Uri(epInfo[2]);
List<Episode> downloading = new List<Episode>();
downloading.Add(new Episode() { Title = epInfo[0], Progress = "0%" });
lvPodDownloads.Items.Add((new Episode() { Title = epInfo[0], Progress = "0%" }));
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
}
}
}
static int intDownloadProgress = new int();
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
intDownloadProgress = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
This is a code sample of the downloading section of the program.
Here is an image of what I have so far:
https://s33.postimg.cc/gthzioxlr/image.png
You should add an extra argument to your ProgressChanged method.
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Episode curEpisode)
{
curEpisode.Progress = $"{e.ProgressPercentage} %";
}
And to modify the handler setting like that:
List<Episode> downloading = new List<Episode>();
var newEpisode = new Episode() { Title = epInfo[0], Progress = "0%" };
downloading.Add(newEpisode);
lvPodDownloads.Items.Add(newEpisode);
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, newEpisode));
}
The static property intDownloadProgress is then useless.
You should also think about using an observable collection for the episode list and using it for the binding via the XAML code.
I'm working on a Windows Form Application. Textbox index can be saved and shown as in ListBox with this code:
private List<FunctionData> funcParamList = new List<FunctionData>();
...
private void addFuncButton_Click(object sender, EventArgs e)
{
FunctionData funcParams = new FunctionData();
funcParams.blabla1name = blabla1.Text;
funcParams.blabla2name = blabla2.Text;
...
if (funcParams.isValid())
{
funcParamList.Add(funcParams);
functionListBox.Items.Add(functionNameBox.Text);
}
Also I collect objects to TextBox again to edit (by clicking ListBox item) with the following code :
private void getParams(FunctionData data)
{
blabla1.Text = data.blabla1name;
blabla2.Text = data.blabla2name;
functionNameBox.Text = data.functionName;
return;
}
private void functionListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (functionListBox.SelectedItem == null) { return; }
foreach (var obj in funcParamList)
{
if (obj.functionName == functionListBox.SelectedItem.ToString())
{
getParams(obj);
}
}
}
And save them to file as JSON with:
private void saveFileButton_Click(object sender, EventArgs e)
{
fileName = fileNameBox.Text;
string jsonFunc = JsonConvert.SerializeObject(funcParamList);
System.IO.File.WriteAllText(#"<blablapath>\" + fileName + ".txt", jsonFunc);
}
There's 'functionName' object in JSON file that I can use it for showing on ListBox.
My question is: How can I load this file buy Native Load/Open File Dialog and show the objects in ListBox and can edit them again?
And here how I've tried to make it with the following code, but it doesn't work:
private void loadFileButton_Click(object sender, EventArgs e)
{
OpenFileDialog loadFileDialog = new OpenFileDialog();
...
if (loadFileDialog.ShowDialog() == DialogResult.OK)
{
string jsonFileName = loadFileDialog.FileName;
string jsonFile = File.ReadAllText(jsonFileName);
dynamic loadedFile = JsonConvert.DeserializeObject(jsonFile);
//if (functionListBox.SelectedItem == null) { return; }
foreach (var obj in loadedFile)
{
if (obj.functionName != null)
{
functionListBox.Items.Add(obj.functionName);
getParams(obj); // I get exception here
funcParamList.Add(loadedFile);
functionListBox.Refresh();
}
}
}
I've solved the problem by casting 'DeserializeObject' as List and it's done. Here the changes:
...
var loadedFile = JsonConvert.DeserializeObject<List<FunctionData>>(jsonFile);
How can I display embedded images when the listView1 SelectedIndexChanged, I need to pull the image name based on the listview item and display it on the picturebox?
My code:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
label1.Text = listView1.SelectedItems[0].SubItems[0].Text + " " +
textBox2.Text;
var myimage = "_" + listView1.SelectedItems[0].SubItems[0].Text;
// new code tryout
// When I try to do it like this Code runs fine
// but no image is displayed on picturebox
object O = Resources.ResourceManager.GetObject("myimage");
pictureBox1.Image = (Image)O;
//no image displayed and no errors
}
else
{
label1.Text = string.Empty;
}
}
The problem here is that you are confusing the string "myimage" with the content of myimage variable.
You should use the variable's content and not the string as the GetObject parameter:
object O = Resources.ResourceManager.GetObject(myimage);
Based on the fact that I don't know how you did fill your ListView, I took the idea of yours and it works fine. Here's a modified code with a screenshot of the result :
private void View_SelectedIndexChanged(object sender, EventArgs e)
{
if (View.SelectedItems.Count > 0)
{
object O = Resources.ResourceManager.GetObject(View.SelectedItems[0].Text);
PicBox.Image = (Image)O;
}
}
my English is not good because I'm Spanish so I'm using a translator if you do not understand something ask me.
my problem is that I'm doing a program with two windows in main window I have a datagrid in the second window I pass information with textbox, the problem is that by passing the total price by multiplying the amount I get a dessert for the price of a dessert, the total price in the datagrid when I passed it round that price, if the price happened 1.20 the program will change to 1.
gives me no error so I'll have to spend the entire program code sorry.
This is the second window
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (Application.Current.Properties["seleccionado"] == null)
{
textBox1.IsEnabled = false;
Postresinfo = new TabladePostre();
}
else
{
Postresinfo = (TabladePostre) (Application.Current.Properties["seleccionado"]);
textBox1.IsEnabled=false;
textBox1.Text = Convert.ToString(Postresinfo.refPostre);
textBox2.Text = Postresinfo.NombrePostre;
textBox3.Text = Convert.ToString(Postresinfo.cantidad);
textBox4.Text = Convert.ToString(Postresinfo.precio);
textBox5.Text = Convert.ToString(Postresinfo.preciototal);
}
LinqdePostresDataContext BasedeDatos;
string filename = "";
private void button1_Click(object sender, RoutedEventArgs e)
{
BasedeDatos(LinqdePostresDataContext)Application.Current.Properties["basedeDatos"];
Postresinfo.NombrePostre = textBox2.Text;
Postresinfo.cantidad = Convert.ToInt32(textBox3.Text);
Postresinfo.precio = Convert.ToDecimal(textBox4.Text);
Postresinfo.preciototal = Convert.ToDecimal(textBox5.Text);
Postresinfo.imagen = filename;
if (Application.Current.Properties["seleccionado"] != null)
{
Postresinfo.refPostre=Convert.ToInt32(textBox1.Text);
}
else
{
BasedeDatos.TabladePostres.InsertOnSubmit(Postresinfo);
}
BasedeDatos.SubmitChanges();
this.Close();
}
decimal precio = 0;
private void button2_Click(object sender, RoutedEventArgs e)
{
precio = Convert.ToDecimal(textBox4.Text);
textBox5.Text = Convert.ToString(precio * Convert.ToDecimal(textBox3.Text));
}
private void button9_Click(object sender, RoutedEventArgs e)
{
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".jpg"; // Default file extension
dlg.Filter = "Text documents (.jpg)|*.jpg"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
filename = dlg.FileName;
ImageSourceConverter conversor = new ImageSourceConverter();
image1.Source = (ImageSource)conversor.ConvertFromString(filename);
}
}
this is the main window:
LinqdePostresDataContext BasedeDatos = new LinqdePostresDataContext();
private void activar(object sender, RoutedEventArgs e)
{
Cargartabla();
}
private void Cargartabla()
{
var postre = (from n in BasedeDatos.TabladePostres
select n);
dataGrid1.ItemsSource = postre;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Application.Current.Properties["seleccionado"] = null;
Ventana2 Ventana2 = new Ventana2();
Ventana2.Show();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
BasedeDatos.TabladePostres.DeleteOnSubmit((TabladePostre)dataGrid1.SelectedItem);
BasedeDatos.SubmitChanges();
Cargartabla();
}
private void Activar2(object sender, EventArgs e)
{
Cargartabla();
}
private void button3_Click(object sender, RoutedEventArgs e)
{
Application.Current.Properties["seleccionado((TabladePostre)dataGrid1.SelectedItem);
Application.Current.Properties["basedeDatos"] = BasedeDatos;
Ventana2 ventana2 = new Ventana2();
ventana2.Show();
}
If you need to know also I have a database with int price, int quantity in the total price in decimal.
thanks for reply, I tried both options have given me but does not work, these are the faults:
Postresinfo.refPostre = float.Parse (textBox1.Text) gives me no errors, the program runs normally and nothing changes
float.TryParse (textBox1.Text, out Postresinfo.refPostre) has these faults:
Error 1 A property, indexer or dynamic member access May not be passed as an out or ref parameter.
Error 2 The best overloaded method match for 'float.TryParse (string, out float)' has some invalid arguments
Error 3 Argument 2: can not convert from 'out int' to 'float out'
I tried the other code and nothing changes, the program runs normally
shane now, I tried this code:
Convert.ToDecimal (textBox1.Text);
but it changes nothing and runs normally.
I've also tried the other code, but nothing changes and the program runs normally
the fault is not textbox1, I think it's because it's in that TextBox5 textbox where I enter the price in decimal and passes it to the datagrid and is the rounded
I'll also attach the column fails me:
<DataGridTextColumn Binding="{Binding Path=preciototal}" Header="Precio Total"/>
thanks.
you got a lot of code here and i'm not sure what is the problem. i understand that you get round value but it'll be helpful to mention the name of the textBox that it happens in it.
i did saw this code:
Postresinfo.refPostre=Convert.ToInt32(textBox1.Text);
in button1_Click which will cause rounding if the value in textBox1.Text is float.
you should do
Postresinfo.refPostre=float.Parse(textBox1.Text);
or
float.TryParse(textBox1.Text, out Postresinfo.refPostre);
because it's a textbox and you might get a value which isn't a number.
if you decide to use Parse then you should do
try
{
Postresinfo.refPostre=float.Parse(textBox1.Text);
}
catch
{
// Show a message or write to log or simething
}
Your problem is that you are converting a price like "1.20" to an int with Convert.ToInt32(textBox1.Text);.
Try change Postresinfo.refPostre to a decimal and use Convert.ToDecimal(textBox1.Text); so use something like this as a FormatException could be thrown:
try
{
Convert.ToDecimal(textBox1.Text);
}
catch (Exception)
{
//Deal with Error
}