I seem to have a problem with two lines of code in my program.
A ThreadStateException occurs at the lines if (o.ShowDialog() == DialogResult.OK) and if(s.ShowDialog() == DialogResult.OK)
The program is supposed to interpret a made up language, but that part of code has not been made yet. Please help, I have no idea what to do!
public class meow : Form
{
TextBox meowbox = new TextBox();
private string titile;
public meow()
{
titile="Tiger goes Meow";
Size = new Size(500, 600);
Text =titile ;
meowbox.Size = new Size(450, 520);
meowbox.Multiline = true;
meowbox.ScrollBars = ScrollBars.Horizontal;
meowbox.WordWrap = true;
meowbox.Location = new Point(25, 10);
//file
MenuItem feow = new MenuItem("File Meow");
MenuItem oeow = new MenuItem("open Meow");
MenuItem seow = new MenuItem("Save Meow");
feow.MenuItems.Add(oeow);
feow.MenuItems.Add(seow);
//run
MenuItem leow = new MenuItem("Meow");
MenuItem ceow = new MenuItem("Check Meow");
MenuItem reow = new MenuItem("Run Meow");
leow.MenuItems.Add(ceow);
leow.MenuItems.Add(reow);
//menu
MainMenu beow = new MainMenu();
Menu = beow;
beow.MenuItems.Add(feow);
beow.MenuItems.Add(leow);
//put it all meow
Controls.Add(meowbox);
//handlers
oeow.Click += new EventHandler(oeow_Click);
seow.Click += new EventHandler(seow_Click);
/*ceow.Click += new EventHandler(ceow_Click);
reow.Click += new EventHandler(reow_Click);*/
}
protected void oeow_Click( object sender, EventArgs e){
Text="Oeow";
OpenFileDialog o = new OpenFileDialog();
if (o.ShowDialog() == DialogResult.OK)
{
Stream file = o.OpenFile();
StreamReader reader = new StreamReader(file);
char[] data = new char[file.Length];
reader.ReadBlock(data, 0, (int)file.Length);
meowbox.Text = new String(data);
reader.Close();
}
Text = titile;
}
protected void seow_Click(object sender, EventArgs e)
{
Text="seow";
SaveFileDialog s = new SaveFileDialog();
if(s.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(s.OpenFile());
writer.Write(meowbox.Text);
writer.Close();
}
Text=titile;
}
public static void Main()
{
Application.Run(new meow());
}
}
If the code you posted is your real program, then the problem is that you aren't setting the thread's apartment state correctly. The main Winforms UI thread must be a single-threaded apartment thread.
Try:
[STAThread]
public static void Main()
{
Application.Run(new meow());
}
Note that ideally, you should just create your Winforms project using the template built into Visual Studio. It will configure the thread correctly for you.
Related
Сannot update form butReset_Click does not work RestoreLayoutFromRegistry from another form. How to do it right? I created one form from another and it is necessary to reset the pivotGridControl settings from 2 forms. I can't reset the settings.
namespace WindowsFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
butReset.Click += new System.EventHandler(butReset_Click);
pivotGridControl1.SaveLayoutToRegistry(regKey);
}
string regKey = "DevExpress\\XtraPivotGrid\\Layouts\\PivotGridLayout";
public Button butLoad = new Button();
public Button butReset = new Button();
public void LoadBtn_Click(object sender, EventArgs e)
{
Form1 fr = new Form1();
Form form = new Form();
form.Show();
ListBox listBox1 = new ListBox();
listBox1.Size = new System.Drawing.Size(200, 100);
listBox1.Location = new System.Drawing.Point(10, 10);
form.Controls.Add(listBox1);
listBox1.MultiColumn = true;
listBox1.SelectionMode = SelectionMode.MultiExtended;
DirectoryInfo dir = new DirectoryInfo(#"E:\");
FileInfo[] files = dir.GetFiles("*.txt");
butReset.Text = "Сбросить настройки";
butReset.Location = new Point(140, 160);
form.Controls.Add(butReset);
butLoad.Text = "Принять";
butLoad.Location = new Point(30, 160);
form.Controls.Add(butLoad);
var fileNamesWithoutExtension = files
.Select(fi => Path.GetFileNameWithoutExtension(fi.Name));
foreach (string fn in fileNamesWithoutExtension)
{
listBox1.Items.Add(fn.ToString());
}
}
private void SaveBtn_Click(object sender, EventArgs e)
{
pivotGridControl1.RestoreLayoutFromRegistry(regKey);
}
static public void butReset_Click(object sender, EventArgs e)
{
Form1 er = new Form1();
er.pivotGridControl1.RestoreLayoutFromRegistry(er.regKey);
//MessageBox.Show("dsdsdfsdf");
}
}
}
Use PivotGridOptionsDataField.Reset() method to Resets all options to their default values. In your case
static public void butReset_Click(object sender, EventArgs e)
{
pivotGridControl1.Reset();
}
Reference document: https://docs.devexpress.com/CoreLibraries/DevExpress.XtraPivotGrid.PivotGridOptionsDataField.Reset
I'm creating a massmailing program basically, and the problem is that if I do it without threads, it obviously freeze and it needs to be able to show user the progress. Without using another class/object it works perfectly fine.
I get a stackoverflowexception:
{Cannot evaluate expression because the current thread is in a stack overflow state.}
on
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
NOTICE: This can probably be missleading because I haven't even created the thread yet but it still get's stackoverflowexception.
This is the code:
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.Windows;
using System.Net.Mail;
namespace Mass_Mail
{
public partial class Form1 : Form
{
Form2 frm = new Form2();
Worker work = new Worker();
public List<String> succed = new List<String>();
public List<String> failed = new List<String>();
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //Skapa och definiera openfiledialog
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //sätt startmappen till skrivbordet
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; //textfiler.
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
textBox1.Text = openFileDialog1.FileName.ToString();
using (StreamReader sr = new StreamReader(openFileDialog1.FileName)) {
String line;
while ((line = sr.ReadLine()) != null)
{
textBox2.AppendText(line + Environment.NewLine);
}
}
}
catch (Exception ex) {
MessageBox.Show("Kunde inte öppna " + ex.Message);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
frm.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
frm.comboBox1.SelectedIndex = 0;
}
private void button4_Click(object sender, EventArgs e)
{
// work.sendmail(textBox6.Text);
}
}
public class Worker
{
public void DoWork()
{
string[] lines = frm1.textBox2.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++)
{
sendmail(lines[i]);
}
}
Form1 frm1 = new Form1();
Form2 frm2 = new Form2();
public void sendmail(String mail)
{
try
{
SmtpClient client = new SmtpClient(frm2.textBox1.Text, int.Parse(frm2.textBox2.Text));
MailMessage msg = new MailMessage(frm1.textBox3.Text, mail);
client.Timeout = decimal.ToInt32(frm2.numericUpDown1.Value);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("", "");
switch (frm2.comboBox1.SelectedIndex)
{
case 0:
client.EnableSsl = true;
break;
case 1:
client.EnableSsl = false;
break;
}
msg.Subject = frm1.textBox4.Text;
msg.Body = frm1.textBox5.Text;
msg.BodyEncoding = UTF8Encoding.UTF8;
msg.IsBodyHtml = true;
client.Send(msg);
frm1.succed.Add(mail);
frm1.label6.Text = "Lyckades: " + frm1.succed.Count.ToString();
}
catch (System.Net.Mail.SmtpException ex)
{
MessageBox.Show("ERROR! " + ex);
frm1.failed.Add(mail);
frm1.label7.Text = "Misslyckades: " + frm1.failed.Count.ToString();
}
catch (System.FormatException e)
{
MessageBox.Show("ERROR! " + e);
frm1.failed.Add(mail);
frm1.label7.Text = "Misslyckades: " + frm1.failed.Count.ToString();
}
}
}
}
I'm going to create a thread of DoWork. I have never done anything like this and I know that the code is pretty bad at the moment. Any kind of help is highly appreciated.
I'm also really new to C# and multi-threading at all.
Form2 only consists of textboxes etc to contain the SMTP settings, no code there.
EDIT:
If I don't create a new object
Worker work = new Worker();
it works perfectly fine!
In your form you create a new worker:
Worker work = new Worker();
But when you create a worker you create a new form:
Form1 frm1 = new Form1();
And it goes on and on until it breaks.
Remove Worker work = new Worker(); from Form 1. Change your Form 1 constructor like this:
Worker _worker;
public Form1()
{
InitializeComponent();
_worker = new Worker(this);
}
Change your worker like this:
public class Worker
{
Form1 _form1;
public Worker(Form1 form1)
{
_form1 = form1;
}
...
And remove Form1 frm1 = new Form1() from your worker.
I am trying to print a variable with a specified font, but the string is null so nothing is visible in the output. please go through the code and help me to find the error
class BasicClass
{
public string str;
public Font fnt;
}
class BasicMethod:BasicClass
{
public void changevalues(string newstr,Font newfnt)
{
str = newstr;
fnt = newfnt;
}
}
class PrintClass:BasicClass
{
public void print()
{
PrintDialog pd = new PrintDialog();
PrintDocument pdoc = new PrintDocument();
PrinterSettings ps = new PrinterSettings();
PaperSize psize = new PaperSize();
pdoc.DefaultPageSettings.Landscape = true;
pd.Document = pdoc;
pd.Document.DefaultPageSettings.PaperSize = psize;
pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage);
DialogResult result = pd.ShowDialog();
if (result == DialogResult.OK)
{
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = pdoc;
ppd.PrintPreviewControl.Zoom = 1.5;
((Form)ppd).WindowState = FormWindowState.Maximized;
DialogResult ppdResult = ppd.ShowDialog();
}
}
void pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
//string str1 = "XYZ";
//Font fnt1 = new Font("Arial", 12.5f);
g.DrawString(str, fnt, new SolidBrush(Color.Black), 10, 10);
}
}
Button Click event
private void button1_Click(object sender, EventArgs e)
{
BasicMethod bm = new BasicMethod();
PrintClass pc = new PrintClass();
Font ft = new System.Drawing.Font("Arial", 12.5f);
bm.changevalues("Hello", ft);
pc.print();
}
i need to get the output Hello
You are setting the values you want in a completely different object from the one where you try to use them.
One way to fix this:
Change the PrintClass so that it inherits the BasicMethod class instead of BasicClass
class PrintClass : BasicMethod
Then change your click handler:
private void button1_Click(object sender, EventArgs e)
{
PrintClass pc = new PrintClass();
Font ft = new System.Drawing.Font("Arial", 12.5f);
pc.changevalues("Hello", ft);
pc.print();
}
This Is the code for Adding the new Item...
private KrystalCafeDatabaseEntities kce = new KrystalCafeDatabaseEntities();
private Byte[] byteBLOBData;
public AddItem()
{
InitializeComponent();
cmbCategory.DataSource = kce.tblItemTypes;
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "ItemType";
}
private void btnUpload_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
fsBLOBFile.Close();
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pbImage.Image = Image.FromStream(stmBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
tblItem Item = new tblItem();
Item.Name = txtName.Text;
Item.Price = decimal.Parse(txtPrice.Text);
Item.Image = byteBLOBData;
Item.ItemType = (int)cmbCategory.SelectedValue;
kce.AddTotblItems(Item);
kce.SaveChanges();
MessageBox.Show("Record Saved! :D");
}
}
}
The program runs normally but the data will only be stored for awhile, then If i either closed my program or edit my code the data I just added will be lost.
One likely error is that KrystalCafeDatabaseEntities opens a transaction and you need to commit that transaction after calling SaveChanges.
I've googled this problem for the past week, it's killing my peace! Please help... EventArrivedEventHandler is stuck in a loop, and if I stop it, then it won't catch events. But when I use a handler method, the thread is still concentrating on the loop, and won't give attention to the new form I'm trying to make in the handler! Strange thing is, if I just use something small, like a MessageBox, it doesn't cause an issue, just trying to instantiate a form causes the buttons to NOT draw. Then shortly after the program stops responding. In case you're wondering where the form code is, it's just a standard form made by .NET, that works everywhere else in the code except for in the event handler.
Thanks!
class MainClass
{
public static void Main()
{
TaskIcon taskbarIcon;
EventWatch myWatcher;
taskbarIcon = new TaskIcon();
taskbarIcon.Show();
myWatcher = new EventWatch();
myWatcher.Start();
Application.Run();
}
}
public class TaskIcon
{
public void Show()
{
NotifyIcon notifyIcon1 = new NotifyIcon();
ContextMenu contextMenu1 = new ContextMenu();
MenuItem menuItem1 = new MenuItem();
MenuItem menuItem2 = new MenuItem();
contextMenu1.MenuItems.AddRange(new MenuItem[] { menuItem1, menuItem2 });
menuItem1.Index = 0;
menuItem1.Text = "Settings";
menuItem1.Click += new EventHandler(notifyIconClickSettings);
menuItem2.Index = 1;
menuItem2.Text = "Exit";
menuItem2.Click += new EventHandler(notifyIconClickExit);
notifyIcon1.Icon = new Icon("app.ico");
notifyIcon1.Text = "Print Andy";
notifyIcon1.ContextMenu = contextMenu1;
notifyIcon1.Visible = true;
}
private static void notifyIconClickSettings(object Sender, EventArgs e)
{
MessageBox.Show("Settings Here");
}
private static void notifyIconClickExit(object Sender, EventArgs e)
{
//taskbarIcon.Visible = false; // BONUS QUESTION: Why can't I hide the tray icon before exiting?
Application.Exit();
}
}
public class EventWatch
{
public void Start()
{
string thisUser = WindowsIdentity.GetCurrent().Name.Split('\\')[1];
WqlEventQuery query = new WqlEventQuery();
query.EventClassName = "__InstanceCreationEvent";
query.Condition = #"TargetInstance ISA 'Win32_PrintJob'";
query.WithinInterval = new TimeSpan(0, 0, 0, 0, 1);
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += new EventArrivedEventHandler(showPrintingForm);
watcher.Start();
}
void showPrintingForm(object sender, EventArrivedEventArgs e)
{
// MessageBox.Show("This will draw just fine");
Form1 myForm;
myForm = new Form1();
myForm.Show(); // This causes a hangup
}
}
My guess would be that the ManagementEventWatcher calls the EventArrived handler from a different thread than the UI thread. Then your showPrintingForm is executed on that thread and accessing UI from a different thread than the UI thread is bad. You need to marshal your code back onto the UI thread.