Ok so i wrote my own photo viewer to open jpg,gif,png files on my computer. However for some reason whenever i set the file association in windows, using the normal properties menu and then selecting my exe it fails to open the program when i click a picture.
I tried debugging by adding message boxes, but sofar it gives no output.
I see the current window loose focus, but nothing appears.
And task manager does not show my process ever opening.
I think windows might be preventing my application from running in some way, iv attempted to disable my antivirus and running it thinking it was that, but no dice.
Program.cs
namespace PictureViewer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args == null || args.Length == 0)
{
//Console.WriteLine("args is null"); // Check for null array
Application.Run(new Form1());
}
else
{
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Application.Run(new Form1(argument));
}
}
}
}
}
Inside Form1 is 2 constructors, 1 with and one without a pram of string then i just do a
Picturebox1.Image = Image.fromFile(pram);
Im quite sure this issent a c# thing, its more of a windows being dumb thing.
Windows 8.1 for refrence.
edit: heres form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PictureViewer
{
public partial class Form1 : Form
{
string curentdirectory = "";
List<string> imageindir;
int curentindex;
public Form1()
{
InitializeComponent();
imageindir = new List<string>();
}
public Form1(string initfile)
{
InitializeComponent();
curentdirectory = initfile.Substring(0, initfile.LastIndexOf("/"));
imageindir = new List<string>();
try
{
this.Text = initfile;
img.Image = Image.FromFile(initfile);
}
catch(Exception ex)
{
MessageBox.Show("ERR");
}
}
private void btnleft_Click(object sender, EventArgs e)
{
try
{
if (--curentindex < 0)
{
curentindex = imageindir.Count - 1;
}
img.Image = Image.FromFile(imageindir[curentindex]);
}
catch (Exception ex)
{
MessageBox.Show("ERR");
}
}
private void btnright_Click(object sender, EventArgs e)
{
try
{
if (++curentindex > imageindir.Count - 1)
{
curentindex = 0;
}
img.Image = Image.FromFile(imageindir[curentindex]);
}
catch (Exception ex)
{
MessageBox.Show("ERR");
}
}
private void getDirFromFileName(string dir)
{
DirectoryInfo di;
di = new DirectoryInfo(curentdirectory);
var directories = di.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (FileInfo d in directories)
{
if(dir == d.Name)
{
curentindex = imageindir.Count;
}
if(validExtension(d.Name))
{
imageindir.Add(d.Name);
}
}
}
private bool validExtension(string val)
{
val = val.ToLower();
if (val.Contains(".jpg") || val.Contains(".jpeg") || val.Contains(".gif") || val.Contains(".png") || val.Contains(".bmp"))
return true;
return false;
}
}
}
There is an error in curentdirectory = initfile.Substring(0, initfile.LastIndexOf("/")); line. the / should be \\. May be the problem is here.
I have tested your code and it works fine. i have uploaded test project here
Editional Details:
Project has created in Visual Studio 2005.
Related
I am working in c-sharp .net and I am working on creating a login screen for my project. I have a text file with login info for all the users. My c-sharp scrip reads that file to a string then cuts it up into two lists, _usernames and _passwords. When the user types their login info and hits login the _usernames[0] and _passwords[0] account info are the only ones that work. What I want it to do is look through all the _usernames for the inputted one, if it finds it then check the _password[same index as _usernames] and if both are the same as what the user submitted then it will add "true" to the richTextBox.
Why is it not correctly reading from the array?
This is my users.txt:
admin,test|
andrew,yeet|
zana,happy|
This is my c-sharp script:
using System;
using System.IO;
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;
namespace BaseUserInterfase
{
public partial class Login : Form
{
string path = Directory.GetCurrentDirectory() + "\\data\\users.txt";
string data;
string[] _usernames = new string[10];
string[] _passwords = new string[10];
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
GetLoginData();
}
private void btnLogin_Click(object sender, EventArgs e)
{
rtbTemp.Text = "";
for(int i = 0; i < _usernames.Length; i++)
{
if(_usernames[i] == null)
{
break;
}
rtbTemp.AppendText("\n" + _usernames[i]);
rtbTemp.AppendText("\n" + tbUsername.Text.ToString());
rtbTemp.AppendText("\n" + _passwords[i]);
rtbTemp.AppendText("\n" + tbPassword.Text.ToString());
if (_usernames[i] == tbUsername.Text.ToString())
{
rtbTemp.AppendText("\nUsername true");
if (_passwords[i] == tbPassword.Text.ToString())
{
rtbTemp.AppendText("\nPassword true");
rtbTemp.AppendText("\ntrue");
return;
}
}
}
rtbTemp.AppendText("\nfalse");
}
public void GetLoginData()
{
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
data = streamReader.ReadToEnd();
}
List<string> _data = data.Split('|').ToList();
_data.RemoveAt(_data.Count - 1);
rtbTemp.AppendText("\n");
Array.Resize<string>(ref _usernames, _data.Count);
Array.Resize<string>(ref _passwords, _data.Count);
foreach (string _item in _data)
{
List<string> userdata = _item.Split(',').ToList();
string username = userdata[0].ToString();
string password = userdata[1].ToString();
Console.WriteLine(_item);
Console.WriteLine(username);
Console.WriteLine(password);
for(int i = 0; i < _data.Count; i++)
{
if(_usernames[i] == null)
{
_usernames[i] = username;
_passwords[i] = password;
break;
}
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
And this is an image of the login screen:
1
Your file contains carriage return characters. Remove them before you split its content
data = streamReader.ReadToEnd().Replace("\r\n", "");
I have a problem. I made a service which monitoring printing jobs in real time. It didn't worked perfect, but I had no big problem. Now I need to change service into Windows Forms program. And I've got a problem with threads.
Error:
System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.'
This error appears on string "PrintQueue.Refresh()".
I can't find where the other thread tries to run.
I tried to set the other thread and start it with MonitoringJobs() procedure but it doesn't work.
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;
using System.Collections.Concurrent;
using System.Data.SqlClient;
using System.Diagnostics;
using System.ServiceProcess;
using System.Management;
using System.Windows;
using System.Printing;
using System.Configuration;
using System.Collections.Specialized;
using System.Threading;
namespace MonitoringPrintJobs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer.Elapsed += GetJobs;
timer.AutoReset = true;
timer.Enabled = true;
}
System.Timers.Timer timer = new System.Timers.Timer(5);
int writeInterval = 1000;
int DefaultWriteInterval = 1000;
bool Logging;
SelectPrinter fSelectPrinter = new SelectPrinter();
ConcurrentDictionary<string, string> QueueJobs = new ConcurrentDictionary<string, string>();//declaration printers jobs dictionary
ConcurrentDictionary<string, DateTime> PrintedJobs = new ConcurrentDictionary<string, DateTime>();
PrintServer printServer = null;
PrintQueueCollection QueuesOnLocalServer = null;
List<PrintQueue> queues = new List<PrintQueue>();
public void MonitoringJobs()
{
//if(queues != null)
foreach (var PrintQueue in queues)
{
PrintQueue.Refresh();
using (var jobs = PrintQueue.GetPrintJobInfoCollection())//wait until collection updates!!!
foreach (var job in jobs)
{
if (!QueueJobs.ContainsKey(job.Name))//if list with printer jobs doesn't contain found job (name)
{//then put name in list with printer jobs
QueueJobs.TryAdd(job.Name, job.JobStatus.ToString());
if (Logging == true)
{
File.AppendAllText(#"D:\Logs\Logging.txt", String.Format("{0} - {1} - {2}{3}", DateTime.Now, job.Name, job.JobStatus, Environment.NewLine));
}
}
else//if list with printer jobs contains found job name
{
if (QueueJobs[job.Name] != job.JobStatus.ToString() && !QueueJobs[job.Name].ToLower().Contains("error"))//if status for this job doesn't exist
{
QueueJobs[job.Name] = job.JobStatus.ToString();//replace job's status
if (Logging == true)
{
File.AppendAllText(#"D:\Logs\Logging.txt", String.Format("{0} - {1} - {2}{3}", DateTime.Now, job.Name, job.JobStatus, Environment.NewLine));
}
}
if (job.JobStatus.ToString().ToLower().Contains("error") && PrintedJobs.ContainsKey(job.Name))
{
var someVar = new DateTime();
PrintedJobs.TryRemove(job.Name, out someVar);
}
}
if (QueueJobs[job.Name].ToLower().Contains("print") && !QueueJobs[job.Name].ToLower().Contains("error"))//if successfully printed
{
PrintedJobs.TryAdd(job.Name, DateTime.Now);
}
}
}
}
private void GetJobs(Object source, System.EventArgs e)
{
writeInterval--;
MonitoringJobs();
if (writeInterval <= 0)
{
writeInterval = DefaultWriteInterval;
PrintedJobs.Clear();
QueueJobs.Clear();
}
}
protected void OnStart()
{
QueuesOnLocalServer = printServer.GetPrintQueues();
writeInterval = 120000;
foreach (var item in fSelectPrinter.SelectetPrinters)
Logging = true;
foreach (var printer in fSelectPrinter.SelectetPrinters)
{
if (string.IsNullOrEmpty(printer))
{
timer.Stop();
Environment.Exit(0);
}
var queue = QueuesOnLocalServer.FirstOrDefault(o => o.FullName.ToUpper() == printer.ToUpper());
if (queue == null)
{
timer.Stop();
Environment.Exit(0);
}
queues.Add(queue);
}
timer.Start();
}
private void button2_Click(object sender, EventArgs e)
{
fSelectPrinter.ShowDialog();
}
private void Form1_Load(object sender, EventArgs e)
{
printServer = new PrintServer();
foreach (PrintQueue pq in printServer.GetPrintQueues())
fSelectPrinter.listBox1.Items.Add(pq.Name);
}
private void button1_Click_1(object sender, EventArgs e)
{
bool StartPrinting = button2.Enabled = false;//turn of select printers form button
if (StartPrinting == false)//StartPrinting == monitoring == true
{
OnStart();
}
else
{
StartPrinting = true;//StartPrinting == monitoring == false
timer.Stop();
}
}
}
}
In this program I tried to get printing jobs statuses and output them in listbox1 and write results with string.Format in file.
On Form1_Load event you are adding things to your fSelectedPrinter.Listbox.
If you items you are adding are coming from a different thread, that will cause an error. Only UI thread can update objects on a form without using SynchornizationContext.
private readonly SynchronizationContext synchronizationContext;
InitializeComponent();
synchronizationContext = SynchronizationContext.Current;
Here is an example:
private async void btnListFiles1_Click(object sender, EventArgs e)
{
if (txtDirectory1.Text == "")
{
MessageBox.Show(InfoDialog.SELECT_DIRECTORY,PROGRAM_NAME);
return;
}
if (!Directory.Exists(txtDirectory1.Text))
{
MessageBox.Show(InfoDialog.DIRECTORY_NOT_EXIST, PROGRAM_NAME);
return;
}
try
{
string fileTypes = (txtFileTypes1.Text == "") ? "" : txtFileTypes1.Text;
string[] files = Directory.GetFiles(txtDirectory1.Text.TrimEnd(),
(fileTypes == "") ? "*.*" : fileTypes,
(chkSub1.Checked) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
listBoxFiles.Items.Clear();
progressBar.Step = 1;
progressBar.Value = 1;
progressBar.Maximum = files.Length + 1;
listBoxFiles.BeginUpdate();
if (txtSearchPattern1.Text != "")
{
string searchPattern = txtSearchPattern1.Text.ToLower();
await System.Threading.Tasks.Task.Run(() =>
{
foreach (string file in files)
{
if (file.ToLower().Contains(searchPattern))
{
AddToListBox(file);
}
}
});
}
else
{
await System.Threading.Tasks.Task.Run(() =>
{
foreach(string file in files)
{
AddToListBox(file);
}
});
}
listBoxFiles.EndUpdate();
progressBar.Value = 0;
}
private void AddToListBox(string item)
{
synchronizationContext.Send(new SendOrPostCallback(o =>
{
listBoxFiles.Items.Add((string)o);
progressBar.Value++;
}), item);
}
I write code to create and connect to VPN using Dotras in C#. It works very good, but when I write code to get connection status, It doesn't work.
I read Dotras document, and write code like example, but It still doesn't work.
It doesn't show status in multiple line textbox. :(
Please show me, what I wrong. Thank you.
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.Threading.Tasks;
using System.Windows.Forms;
using DotRas;
using System.Net;
namespace VPN1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_create_vpn_Click(object sender, EventArgs e)
{
try
{
string vpnuser = txt_vpn_user.Text;
string ip_address = txt_IP.Text;
this.rasPhoneBook1.Open();
RasEntry entry = RasEntry.CreateVpnEntry(vpnuser, ip_address, RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
this.rasPhoneBook1.Entries.Add(entry);
MessageBox.Show("Success");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private RasHandle handle = null;
private void btn_dial_Click(object sender, EventArgs e)
{
this.rasDialer1.EntryName = txt_vpn_user.Text;
string username = txt_user.Text;
string password = txt_pass.Text;
this.rasDialer1.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
try
{
this.rasDialer1.Credentials = new NetworkCredential(username, password);
this.handle = this.rasDialer1.DialAsync();
this.btn_disconnect.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void rasDialer1_StateChanged(object sender, StateChangedEventArgs e)
{
this.txt_status.AppendText(e.State.ToString() + "\r\n");
}
private void rasDialer1_DialCompleted(object sender, DialCompletedEventArgs e)
{
if(e.Cancelled)
{
this.txt_status.AppendText("Cancelled");
}
else if(e.TimedOut)
{
this.txt_status.AppendText("Timeout");
}
else if(e.Connected)
{
this.txt_status.AppendText("Connection successful");
}
else if (e.Error != null)
{
this.txt_status.AppendText(e.Error.ToString());
}
if(!e.Connected)
{
this.btn_disconnect.Enabled = false;
}
}
private void btn_disconnect_Click(object sender, EventArgs e)
{
if(this.rasDialer1.IsBusy)
{
this.rasDialer1.DialAsyncCancel();
}
else
{
RasConnection connection = RasConnection.GetActiveConnectionByHandle(this.handle);
if(connection!=null)
{
connection.HangUp();
}
}
}
}
}
If the events are not firing, the issue might be that the Events are not set in the events section in the properties window of the rasDialer1 control you added to the form (Form1). Using Visual Studio, Enter the design view, click on the rasDialer1 control which reveals the properties of the RasDialer you added, then navigate to events section (marked with a lightening icon) and then set the StateChanged and DialCompleted events.
OR
You can do all this from code simply by
rasDialer.StateChanged += rasDialer1_StateChanged;
rasDialer.DialCompleted += rasDialer1_DialCompleted;
somewhere in the Form1() constructor, where rasDialer1_StateChanged and rasDialer1_DialCompleted are the event handlers in your code.
I'm also anticipating a potential error within your code where accessing UI controls in those event handlers will get you a Cross-thread operation not valid error since they are called from an async operation this.rasDialer1.DialAsync();
The right way of accessing controls from methods called from another thread is below ...
textbox1.Invoke(new Action(() => textbox1.text = "my string"));
Try using dial instead of dialAsync
try:
{
File.WriteAllText("your rasphone.pbk path","")//Add
string vpnuser = txt_vpn_user.Text;
string ip_address = txt_IP.Text;
this.rasPhoneBook1.Open();
RasEntry entry = RasEntry.CreateVpnEntry(vpnuser, ip_address, RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
this.rasPhoneBook1.Entries.Add(entry);
MessageBox.Show("Success");
}
I have made a button using c# to browse files and folders from windows. My sample code is given below. The problem is: when I click on the browse button I am getting the following exception in the line I have marked in the comment in the following code:
An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll
My sample code:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
public class Form1 : Form
{
public Form1()
{
Size = new Size(400, 380);
Button browse = new Button();
browse.Parent = this;
browse.Text = "Browse";
browse.Location = new Point(220, 52);
browse.Size = new Size(6 * Font.Height, 2 * Font.Height);
browse.Click += new EventHandler(ButtonbrowseOnClick);
}
public void ButtonbrowseOnClick(object sender, EventArgs e)
{
int size = -1;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); //getting exception in this line
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size);
Console.WriteLine(result);
}
public static void Main()
{
Application.Run(new Form1());
}
}
Is there anything wrong in the code?
Using [STAThread] attribute at top of your Main method, should solves the problem.
[STAThread] // <--------Add this
public static void Main()
{
Application.Run(new Form1());
}
I have a program that ping and take all the ip address that are active in a LAN i code it with csharp console mode the problem is that when I put it in mode form an error appear in Spinwatch and a error message box appear
Here is the code and error below
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.Net.NetworkInformation;
using System.Threading;
namespace pingagediffusiontest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{ }
private static List<Ping> pingers = new List<Ping>();
private static int instances = 0;
private static object #lock = new object();
private static int result = 0;
private static int timeOut = 250;
private static int ttl = 5;
static void Mains()
{
string baseIP = "192.168.1.";
Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP);
CreatePingers(255);
PingOptions po = new PingOptions(ttl, true);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] data= enc.GetBytes("abababababababababababababababab");
SpinWait wait = new SpinWait();
int cnt = 1;
Stopwatch watch = Stopwatch.StartNew();
foreach (Ping p in pingers) {
lock (#lock) {
instances += 1;
}
p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
cnt += 1;
}
while (instances > 0) {
wait.SpinOnce();
}
watch.Stop();
DestroyPingers();
Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
Console.ReadKey();
}
public static void Ping_completed(object s, PingCompletedEventArgs e)
{
lock (#lock) {
instances -= 1;
}
if (e.Reply.Status == IPStatus.Success) {
Console.WriteLine(string.Concat("Active IP: ", e.Reply.Address.ToString()));
result += 1;
} else {
Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString()))
}
}
private static void CreatePingers(int cnt)
{
for (int i = 1; i <= cnt; i++) {
Ping p = new Ping();
p.PingCompleted += Ping_completed;
pingers.Add(p);
}
}
private static void DestroyPingers()
{
foreach (Ping p in pingers) {
p.PingCompleted -= Ping_completed;
p.Dispose();
}
pingers.Clear();
}
}
}
Error 1 The type or namespace name 'SpinWait' could not be found
Error 3 The type or namespace name 'Stopwatch' could not be found
Error 4 The name 'Stopwatch' does not exist in the current context
Just add the
using System.Diagnostics;
At the top of your file.
Error 3 The type or namespace name 'Stopwatch' could not be found
You need to import following namespace to use StopWatch in your program:
using System.Diagnostics;
as suggested by #CodeCaster in comments - you are missing semicolon to terminate the Console.WriteLine() statement :
Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString())) //missing semicolon
Suggestion : as you have stated you converted code from Console Application to Windows Forms Application it would be nice if you can change/replace all Console.WriteLine() Statements with MessageBox.Show() as shown below:
MessageBox.Show(String.Concat("Non-active IP: ", e.Reply.Address.ToString()));