C# : getting folder name when right click on it - c#

I am developing a windows application, I need to get the Folder name while right clicking on the Folder to do some operations on it .
So far I did the following :
Made a registry subkey in HKKEY_CLASS_ROOT\Folder\shell\(my program name)
Made a registry subkey of my program name\command [the path of my program]
now I made the registry key to be displayed in folder context menu. And in my application I did the following :
1- in program.cs
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 p = new Form1();
if (args.Length > 0)
{
p.pathkey = args[0];
}
Application.Run(p);
}
2- in my form1 :
private string _pathkey;
public string pathkey
{
get { return _pathkey; }
set { _pathkey = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
if (this.pathkey != null)
{
textBox1.Text=pathkey;
}
}
finally :
now when I right click on a folder lets say for example called NEW. then textbox3.text = C:\NEW , so far it works fine but if the folder name is New Folder then textbox3.text = C:\New only not C:\New Folder and that is my problem if args.length > 0 it does only display the the lenght 0 not the full path.

You need to put the %0 in the registry in quotes to force the entire path to be treated as a single argument.
Otherwise, the spaces are treated as argument separators.
You could also call String.Join(" ", args) to manually recombine all of the arguments, but the first way is better.

Related

Opening an exe(windows app) as modal while opening an office document from hard drive

I have an requirement if the user open any office document from his/her hard drive it's should open an an exe(win form application) as a modal window to capture details about the document.
For that I have developed an console app which runs under the client machine, to monitor if any office document file is opening or not. Please find the below code
static void Main(string[] args)
{
var UIAEventHandler = new AutomationEventHandler(OnUIAEvent);
Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent,
AutomationElement.RootElement,
TreeScope.Children, UIAEventHandler);
Console.ReadLine();
Automation.RemoveAllEventHandlers();
}
public static void OnUIAEvent(object src, AutomationEventArgs args)
{
AutomationElement element;
try
{
element = src as AutomationElement;
}
catch
{
return;
}
string name = "";
if (element == null)
name = "null";
else
{
name = element.GetCurrentPropertyValue(
AutomationElement.NameProperty) as string;
}
if (name.Length == 0) name = "< NoName >";
string guid = Guid.NewGuid().ToString("N");
string str = string.Format("{0} : {1}", name, args.EventId.Id);
if ((element.Current.ClassName.Equals("XLMAIN", StringComparison.InvariantCultureIgnoreCase) == true && name.Contains(".xlsx")) || (element.Current.ClassName.Equals("OpusApp", StringComparison.InvariantCultureIgnoreCase) == true && name.Contains(".docx")))
{
Process.Start(#"E:\experiment\TestingWindowsService\UserInfomation\bin\Debug\UserInfomation.exe", element.Current.Name);
//Automation.AddAutomationEventHandler(
// WindowPattern.WindowClosedEvent,
// element, TreeScope.Element, (s, e) => UIAEventHandler1(s, e, guid, name));
Console.WriteLine(guid + " : " + name);
// Environment.Exit(1234);
}
}
if you see in the OnUIAEvent event handler I am using Process.Start to open an exe.It's working as expected. But I want the exe should open as modal to the opened document.The below code is the form load of the exe.
private void Form1_Load(object sender, EventArgs e)
{
this.TopMost = true;
this.CenterToScreen();
}
Is it possible to open the windows application to open as modal to the opened document?
Unless the external application has been coded taken into account your requirement, it will be difficult.
If you have access to the code (which you seem to have), you can include the Form in your console application (see here how to run a winform from console application?).
The easiest option is to start a windows forms project, then change
the output-type to Console Application. Alternatively, just add a
reference to System.Windows.Forms.dll, and start coding:
using System.Windows.Forms;
[STAThread] static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form()); // or whatever
}
The important bit is the [STAThread] on your Main() method, required for full COM support.
You can override the Creator, and add parameters matching the document, or whatever you need to log/monitor.

Starting my programs solution, by opening a file ->right click->open with->my program(or my programs solution)

I am programming, in Microsoft's Visual Studio 2015, in C#.
I am trying to make an Windows Forms application which would be used to open simple .txt, or other type files, and edit them.
But the point being is i want to open my program with : Right click on .txt file->Open with->My program.
The question I have is this, how am I supposed to do that, if I only have the solution file of my program?
And i don't really care, about opening the .txt files when my program is already running. I want to be able to start it, like i mentioned before.
I am using this program as a starting point, from where the next time i will be able to make a simple mp3 player, or such. And as far as i know, people don't usually start an mp3 player program, and then the mp3 player file they want to play. I hope that sheds some light on what i am trying to accomplish.
I have been searching for a solution, and i couldn't find it.
Perhaps it is really easy, but for me, for now, it isn't. Your help is appreciated.
My Program.cs looks like this :
static void Main(string[] args)
{
//with args(user open file with the program)
if(args != null && args.Length > 0)
{
string fileName = args[0];
//check file exists
if (File.Exists(fileName))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 MainForm = new Form1();
MainForm.OpenFile(fileName);
Application.Run(MainForm);
}
//the file does not exist
else
{
MessageBox.Show("The file does not exist!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
//without args
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
If you're asking how to handle opening the file, try this:
-In your Form1.cs, overload your constructor by adding another definition.
public Form1(string fileName)
{
InitializeComponent();
openFileNow(fileName);
}
-Create the openFileNow method (async for extra goodness)
private async void openFileNow(string fileName)
{
try
{
if(fileName.EndsWith(".txt"))
{
//Obviously you'll do something different with an .mp3
using (StreamReader reader = new StreamReader(fileName))
{
txtEditBox.Text = await reader.ReadToEndAsync();
}
}
else
{
MessageBox.Show("Can't open that file.");
}
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
}
-Edit your Program.cs to simply:
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 MainForm;
if (args != null && args.Length > 0)
{
MainForm = new Form1(args[0]);
}
else
{
MainForm = new Form1();
}
Application.Run(MainForm);
}
In Visual Studio, under the project's properties, you can add Command line arguments in the "Debug" section.
If you want to associate a file extension with your application, you do that in the registry. You can do it in C#, but the ClickOnce settings will be so much cleaner.
Go to your project properties -> Publish -> Options -> FileAssociations
Edit
- Note that if you intend to publish with ClickOnce, you'll need to change a few lines in your Program.cs:
string fileName = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
if (fileName != null && fileName.Length > 0)
{
MainForm = new Form1(fileName);
}
If you're simply looking to debug with file associations, try right-clicking a .txt file, Open With... (More Options) and navigate to your .exe from your project's debug folder, i.e.:
C:\VS Projects\MyProject\MyProject\bin\Debug\myProgram.exe
Obviously this is a temporary solution. Enjoy!
In your Form add a button1 (or change it to suit your need) and add the following logic.
whatever file you open, following logic will use your system default program to open them without further asking.
BTW, Form1 doesn't have OpenFile method , you may have gotten it from somewhere. you can remove it or add method definition.
MainForm.OpenFile(filename);
private void button1_Click(object sender, EventArgs e)
{
var fileDialog1 = new OpenFileDialog
{
InitialDirectory = "c:\\",
RestoreDirectory = true
};
if (fileDialog1.ShowDialog() == DialogResult.OK)
{
System.Diagnostics.Process.Start(fileDialog1.FileName);
}
}
if this is not what you are trying to do then you may have to write to Registry for file association. I gave the link in the comment above.

How to use the function to get location of executable path? [duplicate]

This question already has answers here:
How can I get the application's path in a .NET console application?
(30 answers)
Closed 6 years ago.
I created a Form Application and I tried to get the executable path, and I find this :
System.Reflection.Assembly.GetExecutingAssembly().Location;
System.IO.Path.GetDirectoryName;
but when I puted in my code I had a lot of errors .
This is my code :
namespace inst
{
public class Program
{
System.Reflection.Assembly.GetExecutingAssembly().Location;
System.IO.Path.GetDirectoryName;
[STAThread]
static void Main()
{
}
}
It is right where I placed it? And I want to use that location to find a text file, to be able to change, like here:
private void Form1_Load(object sender, EventArgs e)
{
this.Text = File.ReadLines(Program.Path)
.First(x => x.StartsWith("Title=\""))
.Split(new[] { '=', '"' }, StringSplitOptions.RemoveEmptyEntries)[1];
}
The Path is the location of the file text.
So I want to get de location of executable where is a file test.txt, put the location in a variabile and use that variabile in form1 and form2, in my case
Just put the line System.Reflection.Assembly.GetExecutingAssembly().Location; in the Form1_Load method. and use what it returned. By the way if the file you are trying to access is in the same directory as the assembly there is no need to obtain the path. The paths are relative the executing assembly path.
Also in WinForm application it is better to use Application.StartupPath to get the path.
It is not allowed to have a code outside of a method, except of declarations, by the way like yours is:
System.Reflection.Assembly.GetExecutingAssembly().Location;
System.IO.Path.GetDirectoryName;
And also the compiler wouldn't like that it is not a statement at all. you should do something like var value = Something; and not just Something;
Simply declare a String
private string Path
{
get { return Assembly.GetExecutingAssembly().Location.ToString();}
}
then use it where you want
Edit: for the directory path it's this:
private string Path
{
get {return AppDomain.CurrentDomain.BaseDirectory.ToString();}
}
your code will be
namespace inst
{
public class Program
{
private string Path
{
get {return AppDomain.CurrentDomain.BaseDirectory.ToString();}
}
[STAThread]
static void Main()
{
}
}
and you function (who is in the same class Program)
private void Form1_Load(object sender, EventArgs e)
{
this.Text = File.ReadLines(Path)//here the string with the directory path
.First(x => x.StartsWith("Title=\""))
.Split(new[] { '=', '"' }, StringSplitOptions.RemoveEmptyEntries)[1];
}
if you want the variable Path accessible in all other class you can add a static class and add the string declaration as public and you could use it everywhere like this yourStaticClassName.Path

I cannot change image in picturebox c#

I have made a yatzy game in a console application, and I am currently trying to make one in a forms application.
This is what I have so far:
namespace Yatzy
{
public partial class Form1 : Form
{
public static Random kast = new Random();
public static int kast1 = kast.Next(1, 7);
public static int kast2 = kast.Next(1, 7);
public static int kast3 = kast.Next(1, 7);
public static int kast4 = kast.Next(1, 7);
public static int kast5 = kast.Next(1, 7);
public static int kast6 = kast.Next(1, 7);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (kast1 == 1)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning1.png");
}
else if (kast1 == 2)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning2.png");
}
else if (kast1 == 3)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning3.png");
}
else if (kast1 == 4)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning4.png");
}
else if (kast1 == 5)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning5.png");
}
else if (kast1 == 6)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning6.png");
}
else
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning0.png");
}
}
}
}
As you can see, I define the "kast1" and such in the form, and depending on the outcome, it should display different images in the picturebox. I have looked at every post I could find, and all of the solutions were fuss.
I have tried without "this." and I've tried with "= image.FromFile("Pics\terning#.png");"
Nothing works.
There is no need to use Bitmap object just to load images in the PictureBox.Perhaps the more cleaner way of loading images is by using the Load Method of PictureBox.
If I assume the images are in same directory as your application,enclosed in another folder,this would have done the job easily;
this.pictureBox_terning1.Load(#"\Pics\terning1.png");
The Load method requires a valid path that points to an image as argument,and with this there is no need to call Refresh after loading each image.It doesn't matter if the path is absolute or relative,but the thing that matters is that the path should point to an image.
But I would suggest you to create an absolute path to your executable like this;
string apppath=Application.StartupPath;
string imagepath=#"\Pics\terning1.png";
this.pictureBox_terning1.Load(apppath+imagepath);
As you mentioned that even if no errors are encountered,the images are not being loaded,for such a case debugging would be an ideal technique to find where the program runs out of order.
You probably need to call Refresh() on the picturebox control after you change picture source.
It is most likely that the images you want to load are not at the path you are looking at.
image.FromFile("Pics\terning#.png");
Expects that your images reside in {youprojectfolder}\bin\DebugORRelease\Pics.
new Bitmap(#"\Pics\terning1.png");
Expects that you images reside in {most likely c:}\Pics.
So i would suggest to check this first and if this does not work add a Breakpoint (F9) and start debugging (F5) see MSDN for an introduction in debugging
I would also suggest you to replace your if, else if construct with a switch.
Try this code, which I have tried and works(it will get the bin directory of your app then you can replace folders with image directory):
private void pictureBox1_Click(object sender, EventArgs e)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string path1 = path.Replace(#"\bin\Debug\", #"\Pics\");
if (kast1 == 1)
{
this.pictureBox_terning1.Image = new Bitmap(path1 + "terning1.png");
}
//rest of the code
}
And if you dont like replacing then set your pictures to be copied to bin directory by
right clicking on image -> properties -> Copy to output directory -> copy
always
.

Error "Does not contain a static "Main" Method suitable for an entry point [duplicate]

This question already has answers here:
"does not contain a static 'main' method suitable for an entry point"
(10 answers)
Closed 9 years ago.
I got this Error when I try to compile a sourcecode with CodeDom
Does not contain a static "Main" Method suitable for an entry point!
I already googled it and read other answers here, but I dont know how to fix it.
Can someone please help me?
Here is my source code :
http://picz.to/image/ao5n
^ private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog d = new SaveFileDialog();
d.Filter = "Executable (*.exe)|*.exe";
if (d.ShowDialog() == DialogResult.OK)
{
string source = Properties.Resources.source;
CompilerParameters param = new CompilerParameters();
param.CompilerOptions += "/target:winexe" + " " + "/win32icon:" + "\"" + textBox1.Text + "\"";
param.GenerateExecutable = true;
param.ReferencedAssemblies.Add("System.Windows.Forms.dll");
param.ReferencedAssemblies.Add("System.dll");
param.OutputAssembly = d.FileName;
StringBuilder Temp = new StringBuilder();
String InputCode = String.Empty;
InputCode = "MessageBox.Show((1 + 2 + 3).ToString());";
Temp.AppendLine(#"using System;");
Temp.AppendLine(#"using System.Windows.Forms;");
Temp.AppendLine(#"namespace RunTimeCompiler{");
Temp.AppendLine(#"static void Main(string[] args){");
Temp.AppendLine(#"public class Test{");
Temp.AppendLine(#"public void Ergebnis(){");
Temp.AppendLine(InputCode);
Temp.AppendLine(#"}}}}");
CompilerResults result = new CSharpCodeProvider().CompileAssemblyFromSource(param, Temp.ToString());
if (result.Errors.Count > 0) foreach (CompilerError err in result.Errors) MessageBox.Show(err.ToString());
else MessageBox.Show("Done.");
}
}
All C# programs need to contain the Main() method. Essentially this is where the program starts. The code you posted is just a small part of the entire application. You must have removed the location where main had been residing.
MSDN Article on Main
Updated for comments:
A new Windows Form App has a Program class that instantiates the form that you want.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Try copying that over to a new file called program.cs. Make sure that Form1 now points to the form you created in the applications.
Paste this into your class -- if you still get an error, you need to paste the entire class in question, not just a screen capture of the event handler for a button click.
static void Main(string[] args)
{
//do nothing
}
The code you've posted is the click event for a button. A button is usually on a form, and the form must be initialized. If you create a Windows Forms Application it will create a file Program.cs that contains a Main method that starts your form.
When you start a program, the computer needs to know where to actually start running code, that's what the Main() method is for. It is required to run, and that's the error you are receiving.

Categories