I am trying to produce a Windows Application Form via Codedom. I found a great example showing me how to do this for a Console Application but I can't seem to make this work for a Windows Form.
Here is what I have so far:
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string Output = "Out.exe";
Button ButtonObject = (Button)sender;
textBox2.Text = "";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, textBox1.Text);
Textbox1.text Contains the following:
Public Class Form1: Form
{
}
I'm really not sure what else to put... I am very new to this stuff and I can't seem to understand the articles I came across.
If you're new to CodeDom I strongly suggest you to use Linq2CodeDom which allows you to write your code in expressions which later will be translated through CodeDom into VB or C# code. With this library you can write something like this:
public void Generate()
{
var c = new CodeDomGenerator();
c.AddNamespace("Samples")
.AddClass("Form1")
.AddMethod(MemberAttributes.Public | MemberAttributes.Static, ()=>"YourMethodName", Emit.stmt(() => MessageBox.Show("Method Body")));
}
Assuming that you are actually able to create the EXE at the moment (as you are missing some using statements in your Form1 declaration) I would start by adding the entry point, the static Main method that creates and displays a new Form1 instance:
using System;
using System.Windows.Forms;
public class Form1 : Form
{
public static void Main(string[] args)
{
var form1 = new Form1();
Application.Run(form1);
}
}
That should at least get a window appearing when you run your generated EXE. #soandos also has a good point, you should be able to copy and paste from the source created when you create a form in Visual Studio, althought you should remember that VS2008+ uses partial classes so you need to combine the contents of Form1.cs and Form1.Designer.cs.
Related
I'm trying to make a web browser application, but when I relaunch Visual Studio Community 2019, it shows me about 500 errors such as The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?).
I tried reloading Visual Studio Community 2019 a few times, but still doesn't work either.
Some project infos:
Target framework: .NET Framework 4.8
NuGet Packages used: EasyTabs, CefSharp.WinForm
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 CefSharp;
using CefSharp.WinForms;
using EasyTabs;
Just before I post the question, I found out that you need to use .NET Framework 4.7.2 in order to fix the problem.
So you're using easy tabs, I have the code for you. create new windows form project, in the project create another form and rename it AppContainer with the caps and everything, then open the app container with framework 4.7.2 then type in C# code
namespace YOUR_PROGRAM_NAME_HERE
{
public partial class AppContainer : TitleBarTabs
{
public AppContainer()
{
InitializeComponent();
AeroPeekEnabled = true;
TabRenderer = new ChromeTabRenderer(this);
}
// Handle the method CreateTab that allows the user to create a new Tab
// on your app when clicking
public override TitleBarTab CreateTab()
{
return new TitleBarTab(this)
{
// The content will be an instance of another Form
// In our example, we will create a new instance of the Form1
Content = new Form1
{
Text = "New Tab"
}
};
}
// The rest of the events in your app here if you need to .....
}
}
also at the top of where it says using please type using EasyTabs and then type using CefSharp. basically every package code you use you need to refer to that package then add a subtitle for Browser. Next Open Form1.cs and type this Code.
// 2. Important: Declare ParentTabs
protected TitleBarTabs ParentTabs
{
get
{
return (ParentForm as TitleBarTabs);
}
}
type this where the namespace of your code is For example.
namespace YOUR_PROGRAM_NAME_HERE
{
public partial class Form1 : Form
{
// 2. Important: Declare ParentTabs
protected TitleBarTabs ParentTabs
{
get
{
return (ParentForm as TitleBarTabs);
}
}
public object HTMLcodeec { get; }
public Form1()
{
InitializeComponent();
}
now co into the program.cs file in your solution explorer and click on it one you do you need to type the following code
namespace YOUR_PROGRAM_NAME_HERE
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppContainer container = new AppContainer();
// Add the initial Tab
container.Tabs.Add(
// Our First Tab created by default in the Application will have as
content the Form1
new TitleBarTab(container)
{
Content = new Form1
{
Text = "New Tab"
}
}
);
// Set initial tab the first one
container.SelectedTabIndex = 0;
// Create tabs and start application
TitleBarTabsApplicationContext applicationContext = new
TitleBarTabsApplicationContext();
applicationContext.Start(container);
Application.Run(applicationContext);
}
}
}
Now open Form1.cs and go to Form1. Load Event and at the top of it type
ChromiumWebBrowser Browser;
private void Form1_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
//Initialize
CefSharpSettings.LegacyJavascriptBindingEnabled = true; // Enable Register JS Object, -- RegisterAsyncJsObject, RegisterJsObject allow
settings.CachePath = "cache";
settings.CefCommandLineArgs.Add("enable-media-stream", "1"); //Enable WebRTC4
settings.CefCommandLineArgs.Add("disable-gpu", "1");
settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
BrowserSettings browserSettings = new BrowserSettings
{
FileAccessFromFileUrls = CefState.Enabled,
UniversalAccessFromFileUrls = CefState.Enabled,
WebSecurity = CefState.Enabled,
WebGl = CefState.Enabled,
BackgroundColor = (uint)CefState.Enabled,
};
Browser = new ChromiumWebBrowser(AddressText.Text);
this.pContainer.Controls.Add(Browser);
Browser.DownloadHandler = new DownloadHandler();
Browser.Dock = DockStyle.Fill;
Browser.Load("https://ask.com/");
this.AcceptButton = this.NavigateToURL;
Browser.AddressChanged += Browser_AddressChanged;
Browser.TitleChanged += Browser_TitleChanged;
}
before you don any of this please download cefsharp and easy tabs to your project
if you want to see my Browser project I build Go to https://cleverdamontoutube.wixsite.com/downloaddamonic and you can see what iv done
it is a .exe file you can download "if you need any more help subscrie to my youtube channel because ill be making a video on this topic shorrtly"
I am trying to code a program which is executed when a file is right clicked in windows, and then a context menu feature named 'Move to' executes a file in the windows registry HKEY ClASSES. It ought to parse in "%1" as argument when it executes, so that my program knows where the file is located. However, when I compile my single .cs file, the FolderBrowserDialog won't show. I am suspecting that it is because I haven't initialized some kind of form before I call it. Is it possible in some way to choose a folder from a single c# file without including Forms?
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
public class MoveTo : Form
{
public static string current_file_path;
public static string new_file_path;
public static string file_name;
public static void Main(string[] args){
if (args.Length > 0)
{
current_file_path = (string) args[0];
file_name = (string) current_file_path.Replace(Path.GetDirectoryName(Environment.GetCommandLineArgs()[1]), "");
var browser = new FolderBrowserDialog();
if (browser.ShowDialog()==DialogResult.OK)
{
new_file_path = browser.SelectedPath + file_name;
}else
{
Environment.Exit(1);
}
try
{
File.Move(current_file_path, new_file_path);
}catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
If you bypass the argument check and try to show the FBD in a debugger, with this exact code, you will see System.Threading.ThreadStateException: 'Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.'
As per the error message, this exception won't be raised if no debugger is attached. Put an [STAThread] attribute on your Main method, like you normally see in any windows forms app:
[STAThread]
public static void Main(string[] args)
{
...
I also recommend you add an else for your outer if, to show an error if no arguments are passed (otherwise your app will exit silently
I have tried this
byte[] bytes = File.ReadAllBytes("Program.exe");
Assembly assembly = Assembly.Load(bytes);
assembly.EntryPoint.Invoke(null, new object[0]);
Compiles okay but when I run it, it says
"Program not res..."
What im trying todo is run a dll without admin in the context of exeproxy.exe
Also somehow if this could be a function somehow that would be great. im change code to Visual c++
Im using the following
using System;
using System.IO;
using System.Reflection;
namespace exeproxy
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Usage: exeproxy <exe>");
Environment.Exit(1);
}
string exe = args['0'];
byte[] bytes = File.ReadAllBytes(exe);
Assembly assembly = Assembly.Load(bytes);
assembly.EntryPoint.Invoke(null, new object[] { new string[0] });
}
}
}
Useful link
http://www.c-sharpcorner.com/UploadFile/ajyadav123/executing-assembly-code-in-C-Sharp/
It may make more sense to use C++ or VC++ looking at the link for asm().
You can use Calc.exe to test if it works; it's not all about running .net programs.
You should change how you pass the parameters to the EntryPoint. The second parameter to invoke is an array of object that is resolved as the parameters to the Main. But Main takes a array of strings. So your call should be like this:
assembly.EntryPoint.Invoke(null, new object[] { new string[0] });
It works with a simple Program.exe that does printing to console. In case of a more complex program there might be more issues that needs to be handled.
I have been working on a problem for a while now which I cannot seem to resolve so I need some help! The problem is that I am writing a program in C# but I require a function from a Python file I created. This in itself is no problem:
...Usual Stuff
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace Program
{
public partial class Form1 : Form
{
Microsoft.Scripting.Hosting.ScriptEngine py;
Microsoft.Scripting.Hosting.ScriptScope s;
public Form1()
{
InitializeComponent();
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
}
private void doPython()
{
//Step 1:
//Creating a new script runtime
var ironPythonRuntime = Python.CreateRuntime();
//Step 2:
//Load the Iron Python file/script into the memory
//Should be resolve at runtime
dynamic loadIPython = ironPythonRuntime.;
//Step 3:
//Invoke the method and print the result
double n = loadIPython.add(100, 200);
numericUpDown1.Value = (decimal)n;
}
}
}
However, this requires for the file 'first.py' to be wherever the program is once compiled. So if I wanted to share my program I would have to send both the executable and the python files which is very inconvenient. One way I thought to resolve this is by adding the 'first.py' file to the resources and running from there... but I don't know how to do this or even if it is possible.
Naturally the above code will not work for this as .UseFile method takes string arguments not byte[]. Does anyone know how I may progress?
Lets start with the simplest thing that could possibly work, you've got some code that looks a little like the following:
// ...
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
var ironPythonRuntime = Python.CreateRuntime();
var x = py.CreateScriptSourceFromFile("SomeCode.py");
x.Execute(s);
var myFoo = s.GetVariable("myFoo");
var n = (double)myFoo.add(100, 200);
// ...
and we'd like to replace the line var x = py.CreateScriptSourceFromFile(... with something else; If we could get the embedded resource as a string, we could use ScriptingEngine.CreateScriptSourceFromString().
Cribbing this fine answer, we can get something that looks a bit like this:
string pySrc;
var resourceName = "ConsoleApplication1.SomeCode.py";
using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName))
using (var reader = new System.IO.StreamReader(stream))
{
pySrc = reader.ReadToEnd();
}
var x = py.CreateScriptSourceFromString(pySrc);
after along time of searching via google, I decided to poste my problem here.
First: I am total C# Noob. I am using a Macro Recorder from Jitbit and I have no choice to use a different. The Problem is in the Macro Recorder, it is missing some essential things.
Like reading a text file into a variable and paste this variable via Clipboard :-(
However the good thing is, the tool support "some" type of native C# Code
If I open the C# Command I get this:
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
And the C# program has to follow also these rules:
=> This Code MUST contain a class named "Program" with a static method "Main"
I already used google and found code that should do the job but I get errors, I guess the
code doesn`t follow the above rules.
This is what I found and tried:
using System;
using System.IO;
public class Program
{
public static void Main()
{
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("Counter.txt");
string counter = myFile.ReadToEnd();
myFile.Close();
// Load string into clipboard
Clipboard.SetDataObject( counter, true );
}
}
I always get the error : "Line 15: The Name Clipboard is not existing in the context"?!?
I hope that someone can explain a noob (me) what is wrong and what is the correct code.
Thanks.
add reference to System.Windows.Forms
using System;
using System.IO;
using System.Windows.Forms;
public class Program
{
[STAThread]
public static void Main()
{
Clipboard.SetDataObject(File.ReadAllText("Counter.txt"), true);
}
}
Note that to Avoid the ThreadStateException you need to applying the STAThread attribute to your Main() function