MessageBox not showing any text in C Sharp - c#

my message box is supposed pop up and ask the user if they want to download a new version of the application and if they say no, it exits and tells them that they need to download a new copy to continue. If they say yeah, it opens a browser to the aforementioned web address. Right now, the message box pops up and nothing appears. However, whenever I gave the code to my friend and he tried it, it worked. What's wrong here? I compiled with Microsoft Framework 4.0.
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 ProjectTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form1_FormClosing();
}
private void Form1_FormClosing()
{
const string message =
"There's an updated version of this program available. Would you like to download now?";
const string caption = "Please update";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
MessageBox.Show("Program will close now. If you want to use this program please update to the newest version.", "Please update");
this.Close();
}
else if (result == DialogResult.Yes)
{
System.Diagnostics.Process.Start("http://www.google.com");
this.Close();
}
}
}
}

Try this:
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 ProjectTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing()
{
const string message =
"There's an updated version of this program available. Would you like to download now?";
const string caption = "Please update";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
MessageBox.Show("Program will close now. If you want to use this program please update to the newest version.", "Please update");
e.Cancel = false;
}
else if (result == DialogResult.Yes)
{
System.Diagnostics.Process.Start("http://www.google.com");
e.Cancel = false;
}
}
}
}

Related

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

How to connect a gsm modem AUTOMATICALLY to available COM ports (without combobox)

THIS QUESTION MAY SEAM A DUPLICATE, BUT NOT. after a long period of search on internet and no, result, then had to seek for assistance.
All solutions apply to loading available ports in a combo box and the user checks one at a go. But the automation feature then dies.
thus, im looking for assistance on how the modem can connect automatically from the available ports without user interaction (USER FRIENDLINESS)
FOR THE COMBO BOX, IT IS WORKING FINE AS BELOW,
using GsmComm.GsmCommunication;
using GsmComm.PduConverter;
using GsmComm.Server;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace COMM_All
{
public partial class Comm_F : Form
{
public Comm_F()
{
InitializeComponent();
}
private void COM_PORTS()
{
string[] ports = SerialPort.GetPortNames();
txtGPort1.Items.AddRange(ports);
txtGPort2.Items.AddRange(ports);
}
private void Form1_Load(object sender, EventArgs e)
{
COM_PORTS();
}
private void Modem1_Click(object sender, EventArgs e)
{
if (txtGPort1.Text == "") { MessageBox.Show("Invalid Port Name"); return; }
comm = new GsmCommMain(txtGPort1.Text, 9600, 8);
Cursor.Current = Cursors.Default;
bool retry;
do
{
retry = false;
try
{
Cursor.Current = Cursors.WaitCursor; comm.Open(); Cursor.Current = Cursors.Default;
//MessageBox.Show("Modem Connected Sucessfully");
txtGStatus1.Text = "Connected Sucessfully";
comm.EnableMessageNotifications();
MessageBox.Show("Message notifications activated.");
}
catch (Exception)
{
Cursor.Current = Cursors.Default;
if (MessageBox.Show(this, "GSM Modem is not available", "Check",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
retry = true;
else { return; }
}
} while (retry);
}
}
}
Note: Computer has multiple usb devices;

How to properly take image and save image?

I made a Win-Forms application and want to Read a Image from the Webcam and save it to the disk and show it in a picture box. Everything works fine, but when i call the "Capture_Image()" function several times (on button14-click) i get a Error like "Object already in use"
using System;
using System.IO;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Runtime.InteropServices;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
private VideoCapture capture = null;
private Bitmap tempImg = null;
public Form1()
{
InitializeComponent();
capture = new VideoCapture();
}
public void Capture_Image()
{
try
{
capture.Start();
tempImg = capture.QueryFrame().Bitmap;
pictureBox2.Image = tempImg;
pictureBox2.Refresh();
tempImg.Save("C:/FHT59N3/Bildanalyse_Projekt/image.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
capture.Stop();
}
catch (NullReferenceException)
{
string message = "No Camera found";
string title = "Please connect Camera";
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);
}
}
private void button14_Click(object sender, EventArgs e)
{
Capture_Image();
}
Am i doing something wrong with the capture? Why do i get this error

AudioSwitcher API change output device

I made a small gadget with an Arduino that sends 2 values via serial to my c# program (potentiometer value for volume and switch button to change output device). The volume part is already complete but I'm not being able to change between the two output devices (monitor audio and Headphones).
My code at the moment:
using AudioSwitcher.AudioApi.CoreAudio;
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;
namespace Volume
{
public partial class Form1 : Form
{
//msg recieved by serial
String msg;
string[] tokens;
//active device
CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
String PHONES = "Headphones (Razer Kraken USB)";
String COLUNA = "ASUS VP228-4 (NVIDIA High Definition Audio)";
public Form1()
{
//open port for serial msg and start timmer
InitializeComponent();
serialPort1.Open();
timer1.Enabled = true;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//handling of the msg
msg = serialPort1.ReadLine();
tokens = msg.Split('%');
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = tokens[0];
label2.Text = tokens[1];
label6.Text = defaultPlaybackDevice.FullName;
//change volume
defaultPlaybackDevice.Volume = Int32.Parse(tokens[0]);
//change output device
if (tokens[1] == "ON")
{
if (defaultPlaybackDevice.FullName == PHONES)
{
//do nothing
}
else
{
//change to monitor output
}
}
else
{
if (defaultPlaybackDevice.FullName == COLUNA)
{
//do nothing
}
else
{
//change to headphones
}
}
}
}
}
I am using an API called AudioSwitcher.AudioApi.CoreAudio which should allow me to do what I want but I am not being able to find how.
First you need to get all the PlaybackDevices
IEnumerable<CoreAudioDevice> devices = new CoreAudioController().GetPlaybackDevices();
and then you can make a function to change your Default playbackdevice with the fullname like this
private void ChangeOutput(string op)
{
foreach (CoreAudioDevice d in devices)
{
if (d.FullName == op)
d.SetAsDefault();
}
}

c# winform active directory: acces to another form if login succes

i want to create a control from a form where i have login textbox and password textbox, and login button.
when i will enter the active directory account name and its password i want to go to another form.
someone can help me with this please.
in this code example i chose the account for login only.
i want to chose it and type the password and go the destination form by exemple from form (login) to form (user interface).
private void radiobtnAD_CheckedChanged(object sender, EventArgs e)
{
if (radiobtnAD.Checked)
{
try
{
string filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
string[] propertiesToLoad = new string[1] { "name" };
using (DirectoryEntry root = new DirectoryEntry("LDAP://DOMAIN"))
using (DirectorySearcher searcher = new DirectorySearcher(root, filter, propertiesToLoad))
using (SearchResultCollection results = searcher.FindAll())
{
foreach (SearchResult result in results)
{
string name = (string)result.Properties["name"][0];
comboBox1.Items.Add(name);
}
}
}
catch
{
}
}
}
Here is your code, edited.
Verify the textboxes (!string.Empty).
Validate credentials.
Display the form you want depending on user type.
It is easy as pie, when you correctly split your 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 LibXmlSettings.Settings;
using Microsoft.ApplicationBlocks.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.DirectoryServices;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.DirectoryServices.AccountManagement;
namespace GestionnaireDesPlugins
{
public partial class Login : Form
{
public Login(string accountName, string accountPassword)
{
InitializeComponent();
}
private void LoginOnClick(object sender, EventArgs e)
{
if (IsValid())
{
GetUser();
// Do whatever you want
ShowForm();
}
}
private void GetUser()
{
try
{
LdapConnection connection = new LdapConnection("AD");
NetworkCredential credential = new NetworkCredential(txtboxlogin.Text, txtboxpass.Text);
connection.Credential = credential;
connection.Bind();
}
catch (LdapException lexc)
{
String error = lexc.ServerErrorMessage;
MessageBox.Show("error account or password.");
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
private bool IsValid()
{
// Check if the user haven't chosen an account
if (!string.IsNullOrEmpty(txtboxlogin.Text) { return false; }
// Check if the user haven't chosen an account
if (!string.IsNullOrEmpty(txtboxpass.Text)) { return false; }
// Check if the user haven't chosen an account
if (!string.IsNullOrEmpty(comboBox1.Text)) { return false; }
// Check if the password TextBox is empty
if (!string.IsNullOrEmpty(textBox1.Text)) { return false; }
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials(txtboxlogin.Text, txtboxpass.Text);
}
return isValid;
}
private void ShowForm()
{
if (txtboxlogin.Text == "WantedAdminUser")
{
using (AdminForm form2 = new AdminForm())
form2.ShowDialog();
Show();
}
else
{
using (user userform = new user())
userform.ShowDialog();
Show();
}
}
}
}
As said previously, as you are new in C#, here are some advice:
Split your code: methods must be short and separated by purpose. It's easier for you and for any who works on your code
Manage the exception
Dispose objects
Take care about this txtboxlogin.Text == "WantedAdminUser" it's dangerous.
So you have a form with ComboBox filled with account names, a TextBox for password input, and a Button for opening the new form.
Set the TextBox's property PasswordChar to desired mask character:
textBox1.PasswordChar = '*';
Create a new click method for your login-button by double clicking it in the designer. It should create a new handler:
private void loginButton_Click(object sender, EventArgs e)
{
// Check if the user haven't chosen an account
if (comboBox1.Text == "") { return; }
// Check if the password TextBox is empty
if (textBox1.Text == "") { return; }
// Create a new method for checking the account and password, which returns a bool
bool loginSuccess = CheckUserInput(comboBox1.Text.Trim(), textBox1.Text);
if (loginSuccess)
{
// Create a new instance of your user-interface form. Give the account name and password
// to it's constructor
UserForm newForm = new UserForm(comboBox1.Text.Trim(), textBox1.Text.Trim()))
// Show the created UserForm form
newForm.Show();
// Close this login form
this.Close();
}
}
Edit your UserForm form constructor to take 2 string parameters:
public UserForm(string accountName, string accountPassword)
{
InitializeComponent();
// ...
}
Adding the 2 string parameters is optional. Hope this answered your question.
Example of "CheckUserInput":
private bool CheckUserInput(string account, string password)
{
// your conditions...
return true;
}
this is the code of my app :
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 LibXmlSettings.Settings;
using Microsoft.ApplicationBlocks.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.DirectoryServices;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.DirectoryServices.AccountManagement;
namespace GestionnaireDesPlugins
public partial class Login : Form
{
public Login(string accountName, string accountPassword)
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
using (var context = new PrincipalContext(ContextType.Domain, "Domain"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
comboBox1.Items.Add(de.Properties["samAccountName"].Value);
comboBox1.Sorted = true;
}
}
}
// Check if the user haven't chosen an account
if (comboBox1.Text == "") { return; }
// Check if the password TextBox is empty
if (textBox1.Text == "") { return; }
// Create a new method for checking the account and password, which returns a bool
bool loginSuccess = CheckUserInput(comboBox1.Text.Trim(), textBox1.Text);
if (loginSuccess)
{
// Create a new instance of your user-interface form. Give the account name and password
// to it's constructor
UserForm newForm = new UserForm(comboBox1.Text.Trim(), textBox1.Text.Trim()))
// Show the created UserForm form
newForm.Show();
// Close this login form
this.Close();
}
}
}
i solved what i was looking for
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
LdapConnection connection = new LdapConnection("AD");
NetworkCredential credential = new NetworkCredential(txtboxlogin.Text, txtboxpass.Text);
connection.Credential = credential;
connection.Bind();
MessageBox.Show("You are log in");
Hide();
if (txtboxlogin.Text == "WantedAdminUser")
{
using (AdminForm form2 = new AdminForm())
form2.ShowDialog();
Show();
}
else
{
using (user userform = new user())
userform.ShowDialog();
Show();
}
}
catch (LdapException lexc)
{
String error = lexc.ServerErrorMessage;
MessageBox.Show("error account or password.");
}
catch (Exception exc)
{
MessageBox.Show(Convert.ToString(exc));
}

Categories

Resources