I have a Windows Forms Application with a CheckBox and a button. The button will make it so the CodeDOM compiled exe will disable task manager. But if they don't want it to disable, they can uncheck the button. What I'm trying to to is make it so if they uncheck the button it will remove the block of code from the resource file that disables task manager.
This is my resource file:
using System;
using System.Windows.Forms;
using Microsoft.Win32;
static class Program
{
[STAThread]
static void Main()
{
RegistryKey regkey;
string keyValueInt = "1";
string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
try
{
regkey = Registry.CurrentUser.CreateSubKey(subKey);
regkey.SetValue("DisableTaskMgr", keyValueInt);
regkey.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
My main 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 System.CodeDom.Compiler;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string source = Properties.Resources.BaseSource;
if (checkBox1.Checked == false)
{
// Not sure what to put here
}
CompilerResults results = null;
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Executable|*.exe"})
{
if (sfd.ShowDialog() == DialogResult.OK)
{
results = Build(source, sfd.FileName);
}
}
if (results.Errors.Count > 0)
foreach (CompilerError error in results.Errors)
Console.WriteLine("{0} at line {1}",
error.ErrorText, error.Line);
else
Console.WriteLine("Succesfully compiled!");
Console.ReadLine();
}
private static CompilerResults Build(string source, string fileName)
{
CompilerParameters parameters = new CompilerParameters()
{
GenerateExecutable = true,
ReferencedAssemblies = { "System.dll", "System.Windows.Forms.dll" },
OutputAssembly = fileName,
TreatWarningsAsErrors = false
};
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
return provider.CompileAssemblyFromSource(parameters, source);
}
}
}
Instead of replacing part of the source code yourself, you could let the compiler do it for you by leveraging conditional compilation symbols.
You would modify your source file to include a conditional compilation symbol, e.g. DISABLETASKMGR, like this:
using System;
using System.Windows.Forms;
using Microsoft.Win32;
static class Program
{
[STAThread]
static void Main()
{
#if DISABLETASKMGR
RegistryKey regkey;
string keyValueInt = "1";
string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
try
{
regkey = Registry.CurrentUser.CreateSubKey(subKey);
regkey.SetValue("DisableTaskMgr", keyValueInt);
regkey.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
#endif
}
}
Then you set the CompilerOptions based on whether your check box is checked:
private static CompilerResults Build(string source, string fileName, bool disableTaskManager)
{
CompilerParameters parameters = new CompilerParameters()
{
CompilerOptions = disableTaskManager ? "/define:DISABLETASKMGR" : "",
GenerateExecutable = true,
ReferencedAssemblies = { "System.dll", "System.Windows.Forms.dll" },
OutputAssembly = fileName,
TreatWarningsAsErrors = false
};
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
return provider.CompileAssemblyFromSource(parameters, source);
}
This is probably going to be more maintainable than solutions based on text replacements or insertions later. Of course, still another option is to have two source files (one with the optional code and one without it) and select the appropriate one based on the settings selected by the user.
Related
I am trying to do rtsp streaming in Nav 2016 using control add in using VLC player for dotnet. The control gets added on Nav page but i am not able to stream video from IP camera. The same code works fine on windows application but it does not work in Nav. Here is my sample code. please help me if i am doing anything wrong here.
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Dynamics.Framework.UI.Extensibility;
using Microsoft.Dynamics.Framework.UI.Extensibility.WinForms;
using System.Text.RegularExpressions;
using System.IO.Ports;
using WebEye.Controls.WinForms.StreamPlayerControl;
using Vlc.DotNet.Forms;
namespace WeighControl
{
[ControlAddInExport("CamControl")]
public class CamControl : WinFormsControlAddInBase
{
private VlcControl streamCam1;
private delegate void myDelegate(string str);
[ApplicationVisible]
public event MethodInvoker CamControlAddInReady;
[ApplicationVisible]
public void ShowCameraControl()
{
ShowCamera();
}
public CamControl()
{
}
private void ShowCamera()
{
try
{
streamCam1.Play(new Uri("rtsp://admin:admin#192.168.0.171/"));
}
catch(Exception ex)
{
}
}
protected override Control CreateControl()
{
streamCam1 = new VlcControl();
this.streamCam1.AutoSize = true;
this.streamCam1.BackColor = System.Drawing.Color.Black;
this.streamCam1.Spu = -1;
this.streamCam1.ForeColor = System.Drawing.Color.Black;
this.streamCam1.Location = new System.Drawing.Point(1, 416);
this.streamCam1.Margin = new System.Windows.Forms.Padding(2);
this.streamCam1.Name = "streamCam1";
string path = #"C:\Program Files\VideoLAN\VLC";
System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path);
this.streamCam1.VlcLibDirectory = directoryInfo;
this.streamCam1.VlcMediaplayerOptions = null;
this.streamCam1.Size = new System.Drawing.Size(540, 226);
this.streamCam1.TabIndex = 2198;
streamCam1.HandleCreated += (sender, args) =>
{
if (CamControlAddInReady != null)
{
CamControlAddInReady();
}
};
return streamCam1;
}
}
}
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 can I assign filepath to the string file123 using ShowFileDialog();
List<string> lines = File.ReadAllLines(file123).ToList();
foreach(string line in lines)
{
Console.WriteLine(line);
}
What you need.
first Add
using System.Windows.Forms;
to your console project;
then you need to mark
[STAThread]
above your main method.
and tested code below
[STAThread]
static void Main(string[] args)
{
string xyz = string.Empty;
OpenFileDialog openFileDialog = new OpenFileDialog();
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
xyz = openFileDialog.FileName;
Console.WriteLine(xyz);
Console.ReadKey();
}
First you have to add a refrence to System.Windows.Forms.dll for this to work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; // Required to use OpenFileDialog.
using System.IO; // Required to read/write to files.
namespace ConsoleApp1
{
class Program
{
[STAThread] // This attribute is required to access OLE related functions.
static void Main(string[] args)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Multiselect = false;
string file123 = "";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{ file123 = openFileDialog1.FileName; }
List<string> lines = File.ReadAllLines(file123).ToList();
foreach (string line in lines)
{ Console.WriteLine(line); }
Console.ReadKey();
}
}
}
I am fairly new to C# so i don't know how to attack this problem. I have this code, that generates the form so a pop up box comes up and lets you select the folder the user wants to select. The problem is that after its selected it doesn't give an option to hit enter or hit ok so that the rest of my code can use that folder as a path to execute the remainder of what i want to do.
This is the code:
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 PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.IO;
namespace FolderBrowserDialogSampleInCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
var dir = textBox1.Text;
File.SetAttributes(dir, FileAttributes.Normal);
string[] files = Directory.GetFiles(dir, "*.pdf");
IEnumerable<IGrouping<string, string>> groups = files.GroupBy(n => n.Split('.')[0].Split('_')[0]);
foreach (var items in groups)
{
Console.WriteLine(items.Key);
PdfDocument outputPDFDocument = new PdfDocument();
foreach (var pdfFile in items)
{
Merge(outputPDFDocument, pdfFile);
}
if (!Directory.Exists(dir + #"\Merge"))
Directory.CreateDirectory(dir + #"\Merge");
outputPDFDocument.Save(Path.GetDirectoryName(items.Key) + #"\Merge\" + Path.GetFileNameWithoutExtension(items.Key) + ".pdf");
}
Console.ReadKey();
}
}
private static void Merge(PdfDocument outputPDFDocument, string pdfFile)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
outputPDFDocument.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
outputPDFDocument.AddPage(page);
}
}
}
}
What generates the form to come is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace FolderBrowserDialogSampleInCSharp
{
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());
}
}
}
I'm assuming that i either have to add in a button in the form design as "enter" or "ok."
Could i just have this so that as soon as the user selects the folder and hits ok the program proceeds to store that as the user selected path?
The answer i was searching for:
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 PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.IO;
namespace FolderBrowserDialogSampleInCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
var dir = textBox1.Text;
File.SetAttributes(dir, FileAttributes.Normal);
string[] files = Directory.GetFiles(dir, "*.pdf");
IEnumerable<IGrouping<string, string>> groups = files.GroupBy(n => n.Split('.')[0].Split('_')[0]);
foreach (var items in groups)
{
Console.WriteLine(items.Key);
PdfDocument outputPDFDocument = new PdfDocument();
foreach (var pdfFile in items)
{
Merge(outputPDFDocument, pdfFile);
}
if (!Directory.Exists(dir + #"\Merge"))
Directory.CreateDirectory(dir + #"\Merge");
outputPDFDocument.Save(Path.GetDirectoryName(items.Key) + #"\Merge\" + Path.GetFileNameWithoutExtension(items.Key) + ".pdf");
}
Console.Read();
Close();
}
}
private static void Merge(PdfDocument outputPDFDocument, string pdfFile)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
outputPDFDocument.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
outputPDFDocument.AddPage(page);
}
}
}
}
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.