Context Menu item not showing - c#

I am trying to place a new Menuitem in Explorer context menu and I cannot get it to work.
I am not getting any exceptions or error messages and I've set breakpoints and they're not being hit. And I've searched the registry and it's not there. What am I doing wrong?
private const string MenuName = "Folder\\shell\\NewMenuOption";
private const string Command = "Folder\\shell\\NewMenuOption\\command";
private void Form1_Shown(object sender, EventArgs e)
{
using(var folder = new FolderBrowserDialog())
{
if(folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Properties.Settings.Default.ArchivePath = folder.SelectedPath;
Properties.Settings.Default.Save();
RegistryKey regmenu = null;
RegistryKey regcmd = null;
try
{
regmenu = Registry.ClassesRoot.CreateSubKey(MenuName);
if (regmenu != null)
regmenu.SetValue("", "Archive");
regcmd = Registry.ClassesRoot.CreateSubKey(Command);
if (regcmd != null)
regcmd.SetValue("", Environment.CurrentDirectory + #"\Archiver.exe");
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}
finally
{
if (regmenu != null)
regmenu.Close();
if (regcmd != null)
regcmd.Close();
}
}
else
{
if(MessageBox.Show("In order to use Archiver, you must first specify where your archive is. Do you want to continue?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
{
Application.Restart();
}
else
{
this.Dispose(true);
}
}
}
}

Run your app as admin.
Making changes to the register may require admin rights.

Related

OpenFileDialog opening twice in my C# program

I am having a problem with a with a code that I used for my C# application. When I click on the browse button and select the file dialogue box opens twice.
private void txt_location_TextChanged(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
folderPath = folderBrowserDialog1.SelectedPath;
}
}
private void Button21_Click(object sender, EventArgs e)
{
using(var fbd = new FolderBrowserDialog()) {
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) {
selectedPath = fbd.SelectedPath;
txt_location.Text = selectedPath;
}
}
}
private void bunifuThinButton21_Click_1(object sender, EventArgs e)
{
System.IO.StreamWriter file;
bool isvalid = ValidateInputs();
try {
file = new System.IO.StreamWriter(selectedPath + # "\dred.txt");
catch (Exception ex) {
MessageBox.Show("Please, Select valid Path..");
return;
}
try {
if (isvalid) {
WriteLines(file);
}
}
catch (Exception ex2) {
MessageBox.Show(ex2.Message);
}
finally {
file.Close();
}
}
}
Obviously, it is only meant to open once to enable me to read the selected file. This works, but only once I have selected the file twice.
Thanks in advance for your help.
You have FolderBrowserDialog being instantiated and shown on two different events:
txt_location_TextChanged
and
Button21_Click
You're having two popups because each one is firing once separately.
You should probably remove the event txt_location_TextChanged entirely unless you need it for another thing that isn't popping the FolderBrowserDialog again.

c# webbrowser viewer control takes time to dispose

When closing Form containing a WebBrowser control with a Pdf document open in the webbrowser, the form takes some 10 seconds to close. I tracked the issue down to Dispose method of the webbrowser.
private void advBandedGridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if (advBandedGridView1.GetFocusedDataRow() != null)
{
string wordno = advBandedGridView1.GetFocusedDataRow()["wordno"].ToString();
string itemcd = advBandedGridView1.GetFocusedDataRow()["itemcd"].ToString();
for (int i = 0; i < _caseCount; i++)
{
ButtonColoring(wordno, _seqkindCode[i]);
}
LoadPDF(itemcd);
gridControl2.DataSource = null;
gridControl2.RefreshDataSource();
}
}
Control Event
private void LoadPDF(string itemcd)
{
try
{
ReturnPacket rp;
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = 'EYE'", false);
if (rp.DataTables.Count > 0 && rp.DataTables[0].Rows.Count == 0)
{
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = '1'", false);
}
if (rp.DataTables[0].Rows.Count > 0)
{
string dockind = string.Empty;
dockind = rp.DataTables[0].Rows[0]["code"].ToString();
ParameterCollection paramCol = new ParameterCollection();
paramCol.Add("p_itemcd", itemcd);
paramCol.Add("p_dockind", dockind);
PdfFileInfo temp_fileInfo = biz.SelectInspectionStandards(paramCol);
if (temp_fileInfo != null)
{
if (_fileInfo != null && temp_fileInfo.FileNm == _fileInfo.FileNm)
{
WebBrowserPdf.Visible = true;
return;
}
_fileInfo = null;
_fileInfo = temp_fileInfo;
PDF_FILE_PATH = FilePath + _fileInfo.FileNm;
DirectoryInfo di = new DirectoryInfo(FilePath);
if (di.Exists == false)
{
di.Create();
}
if (!File.Exists(PDF_FILE_PATH))
File.WriteAllBytes(PDF_FILE_PATH, _fileInfo.FileData);
if (!PDF_FILES.Contains(PDF_FILE_PATH))
{
PDF_FILES.Add(PDF_FILE_PATH);
}
WebBrowserPdf.Navigate(PDF_FILE_PATH + "?#zoom=" + _zoomFactor + "%", false);
WebBrowserPdf.Visible = true;
simpleButtonOpenPOPUP.Enabled = true;
}
else
{
WebBrowserPdf.Visible = false;
simpleButtonOpenPOPUP.Enabled = false;
}
}
}
catch (Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Alert, true);
}
}
it is Load Method
private void w_pcmu081_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
WebBrowserPdf.Dispose();
Process[] Pro = Process.GetProcessesByName("osk");
if (Pro.GetLength(0) > 0)
Pro[0].Kill();
}
catch(Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Info, true, null, true);
}
}
Closing
The same situation happened to me.
Adobe has done something wrong in the latest version of Acrobat Reader DC (15.023.20056).
If you uncheck option Enable Protected Mode at startup in Edit -> Preferences -> Security (Enhanced), everything will be back to normal.
On my case it is not a solution.
More info here: https://forums.adobe.com/thread/2267688

create folder firing two times

My app two way sync app when iam created new folder from desktop it is some time creating extra folder with name "New folder "
private void FileSystemWatcherCreated(object sender, FileSystemEventArgs e)
{
try
{
var parentDirectory = Directory.GetParent(e.FullPath).FullName;
if (!this.IsWatchedObject(e.FullPath))
{
return;
}
if (!this.IsFileOrDirectoryExists(e.FullPath))
{
if (!string.IsNullOrWhiteSpace(e.FullPath))
{
this.Debug("FileSystemWatcherCreated", "Delete '{0}' from the icon overlay system...", e.FullPath);
var success = CloudFuzeIconOverlayAssystent.DeleteFileFolderRecord(e.FullPath, true, this.LogService);
this.Debug("FileSystemWatcherCreated", success.BooleanToSuccessFailLogString());
this.SendFileSystemItemChangedRecursively(e.FullPath);
}
return;
}
else
{
if (Directory.Exists(e.FullPath))
{ //http://stackoverflow.com/questions/16301598/filesystemwatcher-files-in-subdirectory
foreach (string file in Directory.GetFiles(e.FullPath))
{
var eventArgs = new FileSystemEventArgs(
WatcherChangeTypes.Created,
Path.GetDirectoryName(file),
Path.GetFileName(file));
FileSystemWatcherCreated(sender, eventArgs);
}
}
}
if (this.IsFileFolderAddedToRootFolder(this.cloudFuzeDirectory, e.FullPath))
{
return;
}
if (this.cloudFuzeDirectory == parentDirectory)
{
return;
}
var type = Directory.Exists(e.FullPath) ? WellKnownFileFoderTypes.Folder : WellKnownFileFoderTypes.File;
this.Debug("FileSystemWatcherCreated", "Add '{0}' in the queue for registration in the local storage...", e.FullPath);
this.addedFileFolders.Enqueue(new FileFolder
{
SavedFilePath = e.FullPath,
FileType = type,
Type = type
});
}
catch (Exception exc)
{
this.Error("FileSystemWatcherCreated", exc);
}
}

c# updater help ( restart once update is complete )

Hello all i have managed to make a basic program that will do a update for me but one thing i want to try and do when the update form is open to close the main form then restart program when the update is finished but have no idea how to do this
this is the code i have currently
namespace update_test
{
public partial class Form1 : Form
{
// folder calls needed
string updatepath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "updatetest");
public Form1()
{
InitializeComponent();
}
// copying files
private static void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, true);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
public void downloadfile()
{
//client.DownloadFile("http://elfenliedtopfan5.co.uk/update/elfenlied_weapons.zip", updatepath);
WebClient client = new WebClient();
string file = Path.Combine(updatepath, "elfenlied_weapons.zip");
client.DownloadFileAsync(new Uri("http://elfenliedtopfan5.co.uk/update/elfenlied_weapons.zip"), file);
client.DownloadProgressChanged += client_DownloadProgressChanged;
MessageBox.Show(file);
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
int bytesin = int.Parse(e.BytesReceived.ToString());
int totalbytes = int.Parse(e.TotalBytesToReceive.ToString());
int kb1 = bytesin / 1024;
int kb2 = totalbytes / 1024;
label1.Text = kb1.ToString() + "KB out of " + kb2.ToString() + "KB (" +e.ProgressPercentage.ToString() + "%)";
progressBar1.Value = e.ProgressPercentage;
if (e.ProgressPercentage == 100)
{
exactzip();
}
}
public void update()
{
string downloadurl = "";
Version newversion = null;
string xmlurl = "http://elfenliedtopfan5.co.uk/xml/update.xml";
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlurl);
reader.MoveToContent();
string elementname = "";
if ((reader.NodeType == XmlNodeType.Element)&& (reader.Name == "update_test"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
elementname = reader.Name;
}
else
{
if((reader.NodeType == XmlNodeType.Text)&& (reader.HasValue))
{
switch (elementname)
{
case "version":
newversion = new Version(reader.Value);
break;
case "url":
downloadurl = reader.Value;
break;
}
}
}
}
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (reader != null)
reader.Close();
}
Version applicationvershion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (applicationvershion.CompareTo(newversion) < 0)
{
DialogResult dialogResult = MessageBox.Show("Version " + newversion.Major + "." + newversion.Minor + "." + newversion.Build + " of elfenliedprograms do you want to update now ?", "Update Avalible!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
var myForm = new Form1();
myForm.Show();
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
else
{
MessageBox.Show("program currently upto date :) ");
}
}
}
public void seeiffile()
{
// Set to folder path we must ensure exists.
string updatepathex = updatepath;
try
{
// If the directory doesn't exist, create it.
if (!Directory.Exists(updatepathex))
{
Directory.CreateDirectory(updatepathex);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
// if all above works then follow this
public void exactzip()
{
using (ZipFile zip = ZipFile.Read (Path.Combine(updatepath, "elfenlied_weapons.zip")))
{
foreach (ZipEntry e in zip)
{
e.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
e.Extract(updatepath);
// e.Extract(updatepath);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
seeiffile();
downloadfile();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
ShowHideForm1(true);
}
private void ShowHideForm1(bool show)
{
Form1 f1 = Application.OpenForms.OfType<Form1>().SingleOrDefault();
if (f1 != null)
{
if (show)
{ f1.Show(); }
else
{ f1.Hide(); }
}
}
private void Form2_Shown(object sender, EventArgs e)
{
ShowHideForm1(false);
}
}
}
then i have another form attached to this application called
elfenliedprograms.cs
witch contains this code
namespace update_test
{
public partial class elfenliedprograms : Form
{
public elfenliedprograms()
{
InitializeComponent();
}
private void elfenliedprograms_Load(object sender, EventArgs e)
{
update();
}
public void update()
{
string downloadurl = "";
Version newversion = null;
string xmlurl = "http://elfenliedtopfan5.co.uk/xml/update.xml";
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlurl);
reader.MoveToContent();
string elementname = "";
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "update_test"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
elementname = reader.Name;
}
else
{
if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue))
{
switch (elementname)
{
case "version":
newversion = new Version(reader.Value);
break;
case "url":
downloadurl = reader.Value;
break;
}
}
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (reader != null)
reader.Close();
}
Version applicationvershion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (applicationvershion.CompareTo(newversion) < 0)
{
DialogResult dialogResult = MessageBox.Show("Version "+ newversion.Major + "." + newversion.Minor + "." + newversion.Build + " of elfenliedprograms do you want to update now ?", "Update Avalible!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
var myForm = new Form1();
myForm.Show();
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
else
{
MessageBox.Show("program currently upto date :) ");
}
}
}
so basically once the update triggers there is a update it will call elfenliedprograms.cs but it will not shut down the main form if i do that it will shut the whole process down and im not sure how to go about making it download then restart app so all new stuff is updated it has taken me a good 4 months just to get this working the way i want not very good when it comes to updating a aplication so i would need help on this part sorry to be a pain and ask
thank you for

C# child form not refreshing

I have this code that works fine when I call it from within the form, however, when I call the same from the Parent it runs through the code without results:
public void hideHelp()
{
//Check in db if panel1 is visible
SqlCeCommand checkHelp = new SqlCeCommand("Select Show_Help from Options where Opt_Id = 1", this.optionsTableAdapter.Connection);
if (this.optionsTableAdapter.Connection.State == ConnectionState.Closed)
{ this.optionsTableAdapter.Connection.Open(); }
try
{
bool showHelp = (bool)(checkHelp.ExecuteScalar());
this.panel1.Visible = showHelp;
this.Refresh();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
On Main form I have a toggle button with the following code:
private void tglHelp_Click(object sender, EventArgs e)
{
if (tglHelp.ToggleState.ToString() == "On")
{
HRDataSet.OptionsRow updateHelp = hRDataSet.Options.FindByOpt_Id(1);
try
{
updateHelp.Show_Help = true;
this.optionsTableAdapter.Update(this.hRDataSet);
Form activeChild = this.ActiveMdiChild;
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName);
}
tglHelp.Text = "Help Panel \nOFF";
}
Any ideas?
In this piece of code
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
you open another frmAddEmployees and add to the MDI, but you don't show it.
If your intent was to call the code in the current frmAddEmployees identified by the activeChild you should use something like this
if (activeChild.Name == "frmAddEmployees")
{
((frmAddEmployees)activeChild).hideHelp();
}

Categories