Ways of displaying exe icons in a ListView - c#

Using a ListView, I need to display (large) icons for an array of executables.
Is there a standard way of doing this / a "Pattern" (whether Design or otherwise)?
A wrinkle: these .exes should be runnable from this ListView ONLY. If a person were to navigate to the .exe via Explorer, they should not be able to run them from there. IOW, the user must log in to the system before seeing the array of program icons (and what they see will depend on their role)*, and that is the ONLY gateway to run those apps.
So, these app icons must be added programmatically.
Ideas?
Update:
Trying to use the code below to create a "Quick and Dirty" app.
Here's my 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 System.IO;
namespace ListViewWithAppIcons {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
DirectoryInfo dir = new DirectoryInfo(#"C:\SpotRun");
foreach (FileInfo file in dir.GetFiles()) {
try {
this.imageList1.Images.Add(Image.FromFile(file.FullName));
} catch {
Console.WriteLine("This is not a Duck-billed Platypus");
}
}
this.listView1.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(32, 32);
this.listView1.LargeImageList = this.imageList1;
//or
//this.listView1.View = View.SmallIcon;
//this.listView1.SmallImageList = this.imageList1;
for (int j = 0; j < this.imageList1.Images.Count; j++) {
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
this.listView1.Items.Add(item);
}
}
}
}
..and here's the "code generated by a tool" (not me, the other tool):
namespace ListViewWithAppIcons {
partial class Form1 {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
this.listView1 = new System.Windows.Forms.ListView();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// listView1
//
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView1.Location = new System.Drawing.Point(0, 0);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(555, 408);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(555, 408);
this.Controls.Add(this.listView1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ImageList imageList1;
}
}

Hi Clay, I need to reference a superfluous Princess Bride!
An example off MSDN so you know your coding it up sweet:
private void Form_Load(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(#"c:\pic");
foreach (FileInfo file in dir.GetFiles())
{
try
{
this.imageList1.Images.Add(Image.FromFile(file.FullName));
}
catch
{
Console.WriteLine("This is not an image file");
}
}
this.listView1.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(32, 32);
this.listView1.LargeImageList = this.imageList1;
//or
//this.listView1.View = View.SmallIcon;
//this.listView1.SmallImageList = this.imageList1;
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
this.listView1.Items.Add(item);
}
}
To prevent people from opening the exe's (except from your program) is pretty hard, it would be easy if you wrote all those applications and could require a secret argument (as in like a command line arg) be passed in to start the other applications. But using Process Monitor/Explorer users could find out the secret key.
Alternatively you could hide the exe's in some folder but the trick here is that the name of the exe will be shown in Task Manager and once users see this they could search for the exe. I mean you could get around this using my technique here, but how deep is the rabits hole: How to hide C# application from taskmanager processtab? - see my answer, its got the most votes.
Maybe a better solution than all this mucking around hiding stuf from users would be - Kiosk mode: http://support.microsoft.com/kb/555463

Related

Datagridview is not populating when submitting from winform search button

I currently have a C# winform that is compiling with zero errors and zero warnings:
This is my first go at a winform project:
Note: I have a similar project in ASPX that is working as expected
However this one needs to be in a winform.
I also need to start off with an empty datagrid because in the production environment the table we will be calling holds millions of rows.
(this cannot be a filter the datagrid type solution it would kill the server in production.)
the winform is super simple consisting of:
a form: GetParentID
a Text box: textBoxValueToSearch
a button: BTN_SEARCH
a data grid view: ParentIDOutput
a connection string in app.config : RCPDEV (tested and working)
Problem: when I enter a value in the text box and click on the search button I'm expecting a single Parent_Container_Id to be returned in the data grid view. However clicking on the button does nothing.
I have tested the stored procedure code and this is working properly:
Images:
get parent id stored procedure code
get parent id win form
IN PROGRAM.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace GetParentID
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new GetParentID());
}
}
}
IN GETPARENTID.DESIGNER.CS
namespace GetParentID
{
partial class GetParentID
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBoxValueToSearch = new System.Windows.Forms.TextBox();
this.BTN_SEARCH = new System.Windows.Forms.Button();
this.ParentIDOutput = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.ParentIDOutput)).BeginInit();
this.SuspendLayout();
//
// textBoxValueToSearch
//
this.textBoxValueToSearch.Location = new System.Drawing.Point(31, 22);
this.textBoxValueToSearch.Name = "textBoxValueToSearch";
this.textBoxValueToSearch.Size = new System.Drawing.Size(268, 20);
this.textBoxValueToSearch.TabIndex = 0;
//
// BTN_SEARCH
//
this.BTN_SEARCH.Location = new System.Drawing.Point(305, 20);
this.BTN_SEARCH.Name = "BTN_SEARCH";
this.BTN_SEARCH.Size = new System.Drawing.Size(75, 23);
this.BTN_SEARCH.TabIndex = 1;
this.BTN_SEARCH.Text = "Search";
this.BTN_SEARCH.UseVisualStyleBackColor = true;
//
// ParentIDOutput
//
this.ParentIDOutput.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.ParentIDOutput.Location = new System.Drawing.Point(31, 69);
this.ParentIDOutput.Name = "ParentIDOutput";
this.ParentIDOutput.Size = new System.Drawing.Size(349, 67);
this.ParentIDOutput.TabIndex = 2;
//
// GetParentID
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(408, 299);
this.Controls.Add(this.ParentIDOutput);
this.Controls.Add(this.BTN_SEARCH);
this.Controls.Add(this.textBoxValueToSearch);
this.Name = "GetParentID";
this.Text = "GetParentID";
((System.ComponentModel.ISupportInitialize)(this.ParentIDOutput)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBoxValueToSearch;
private System.Windows.Forms.Button BTN_SEARCH;
private System.Windows.Forms.DataGridView ParentIDOutput;
}
}
IN GETPARENTID.CS
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GetParentID
{
public partial class GetParentID : Form
{
public GetParentID()
{
InitializeComponent();
}
BindingSource binder = new BindingSource();
private void BTN_SEARCH_Click(object sender, EventArgs e)
{
// SqlConnection sqlCon = new SqlConnection(RCPDEV)
string constr;
string containerIdValue = textBoxValueToSearch.Text;
constr = Properties.Settings.Default.RCPDEV;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("RFID_GET_CONTAINER_PARENT_ID", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CONTAINER_ID", SqlDbType.NVarChar, 25).Value = containerIdValue;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
ParentIDOutput.DataSource = binder;
binder.DataSource = dataTable;
con.Close();
//FillDataGridView();
}
}
}
Any ideas on what the heck I am doing wrong here
/ i have been pulling my hair out for the last 16 hours or so trying many different things and reading whole lot of articles/tutorials/and help tickets to no avail.
I am at your mercy a to being able to fix this.
You should subscribe event like Control.Click to response any action by user on winform control.
// BTN_SEARCH
//
this.BTN_SEARCH.Click += BTN_SEARCH_Click;
Or you can subscribe MouseClick.
You should look into Control.Event list to find out what event fit into your situation.
You can subscribe event on Properties Window instead write code.

Need help linking navigation pages to navigation bar (Windows Forms/DevExpress)

I'm working through the following tutorial:
https://documentation.devexpress.com/WindowsForms/116628/Build-an-Application/Choose-Application-UI/Office-Inspired-UI/How-to-Build-an-Office-inspired-UI-manually
I've achieved the desired output at step 8 (linking the office navigation bar and navigation bar controls), but I'm having trouble achieving the desired output at step 10 (changing the navigation page to display the different labels depending on the selected navigation bar group).
Here's my Form1.Designer.cs:
namespace dev_express_again
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.navigationFrame1 = new DevExpress.XtraBars.Navigation.NavigationFrame();
this.navigationPage1 = new DevExpress.XtraBars.Navigation.NavigationPage();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.navigationPage2 = new DevExpress.XtraBars.Navigation.NavigationPage();
this.labelControl2 = new DevExpress.XtraEditors.LabelControl();
this.navBarControl1 = new DevExpress.XtraNavBar.NavBarControl();
this.navBarGroup1 = new DevExpress.XtraNavBar.NavBarGroup();
this.navBarGroup2 = new DevExpress.XtraNavBar.NavBarGroup();
this.officeNavigationBar1 = new DevExpress.XtraBars.Navigation.OfficeNavigationBar();
((System.ComponentModel.ISupportInitialize)(this.navigationFrame1)).BeginInit();
this.navigationFrame1.SuspendLayout();
this.navigationPage1.SuspendLayout();
this.navigationPage2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.navBarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.officeNavigationBar1)).BeginInit();
this.SuspendLayout();
//
// navigationFrame1
//
this.navigationFrame1.Controls.Add(this.navigationPage1);
this.navigationFrame1.Controls.Add(this.navigationPage2);
this.navigationFrame1.Location = new System.Drawing.Point(146, 0);
this.navigationFrame1.Name = "navigationFrame1";
this.navigationFrame1.Pages.AddRange(new DevExpress.XtraBars.Navigation.NavigationPageBase[] {
this.navigationPage1,
this.navigationPage2});
this.navigationFrame1.SelectedPage = this.navigationPage1;
this.navigationFrame1.Size = new System.Drawing.Size(462, 311);
this.navigationFrame1.TabIndex = 0;
this.navigationFrame1.Text = "navigationFrame1";
//
// navigationPage1
//
this.navigationPage1.Caption = "navigationPage1";
this.navigationPage1.Controls.Add(this.labelControl1);
this.navigationPage1.Name = "navigationPage1";
this.navigationPage1.Size = new System.Drawing.Size(462, 311);
this.navigationPage1.Tag = "Employees";
//
// labelControl1
//
this.labelControl1.Location = new System.Drawing.Point(190, 145);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(33, 13);
this.labelControl1.TabIndex = 0;
this.labelControl1.Text = "Page 1";
//
// navigationPage2
//
this.navigationPage2.Caption = "navigationPage2";
this.navigationPage2.Controls.Add(this.labelControl2);
this.navigationPage2.Name = "navigationPage2";
this.navigationPage2.Size = new System.Drawing.Size(462, 311);
this.navigationPage2.Tag = "Customers";
//
// labelControl2
//
this.labelControl2.Location = new System.Drawing.Point(194, 135);
this.labelControl2.Name = "labelControl2";
this.labelControl2.Size = new System.Drawing.Size(33, 13);
this.labelControl2.TabIndex = 0;
this.labelControl2.Text = "Page 2";
//
// navBarControl1
//
this.navBarControl1.ActiveGroup = this.navBarGroup1;
this.navBarControl1.Groups.AddRange(new DevExpress.XtraNavBar.NavBarGroup[] {
this.navBarGroup1,
this.navBarGroup2});
this.navBarControl1.Location = new System.Drawing.Point(0, 0);
this.navBarControl1.Name = "navBarControl1";
this.navBarControl1.OptionsNavPane.ExpandedWidth = 140;
this.navBarControl1.PaintStyleKind = DevExpress.XtraNavBar.NavBarViewKind.NavigationPane;
this.navBarControl1.Size = new System.Drawing.Size(140, 311);
this.navBarControl1.TabIndex = 1;
this.navBarControl1.Text = "navBarControl1";
//
// navBarGroup1
//
this.navBarGroup1.Caption = "Employees";
this.navBarGroup1.Expanded = true;
this.navBarGroup1.Name = "navBarGroup1";
//
// navBarGroup2
//
this.navBarGroup2.Caption = "Customers";
this.navBarGroup2.Name = "navBarGroup2";
//
// officeNavigationBar1
//
this.officeNavigationBar1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.officeNavigationBar1.Location = new System.Drawing.Point(0, 317);
this.officeNavigationBar1.Name = "officeNavigationBar1";
this.officeNavigationBar1.NavigationClient = this.navBarControl1;
this.officeNavigationBar1.Size = new System.Drawing.Size(608, 45);
this.officeNavigationBar1.TabIndex = 2;
this.officeNavigationBar1.Text = "officeNavigationBar1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(608, 362);
this.Controls.Add(this.officeNavigationBar1);
this.Controls.Add(this.navBarControl1);
this.Controls.Add(this.navigationFrame1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.navigationFrame1)).EndInit();
this.navigationFrame1.ResumeLayout(false);
this.navigationPage1.ResumeLayout(false);
this.navigationPage1.PerformLayout();
this.navigationPage2.ResumeLayout(false);
this.navigationPage2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.navBarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.officeNavigationBar1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private DevExpress.XtraBars.Navigation.NavigationFrame navigationFrame1;
private DevExpress.XtraBars.Navigation.NavigationPage navigationPage1;
private DevExpress.XtraBars.Navigation.NavigationPage navigationPage2;
private DevExpress.XtraNavBar.NavBarControl navBarControl1;
private DevExpress.XtraNavBar.NavBarGroup navBarGroup1;
private DevExpress.XtraNavBar.NavBarGroup navBarGroup2;
private DevExpress.XtraBars.Navigation.OfficeNavigationBar officeNavigationBar1;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.LabelControl labelControl2;
}
}
And my Form1.cs:
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 dev_express_again
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
navigationPage1.Tag = navBarGroup1.Caption = navigationPage1.Caption = "Employees";
navigationPage2.Tag = navBarGroup2.Caption = navigationPage2.Caption = "Customers";
officeNavigationBar1.NavigationClient = navBarControl1;
}
private void navBarControl1_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
{
navigationFrame1.SelectedPage = (DevExpress.XtraBars.Navigation.NavigationPage)navigationFrame1.Pages.FindFirst(x => (string)x.Tag == e.Group.Caption);
}
}
}
Both are exactly the same as the tutorial, as far as I can see. When I run the code, I get a window that looks exactly like the one in the tutorial. When I change the selection in the office navigation bar, it reflects in the navigation bar control, but does not change the navigation page.
Any ideas as to what I'm missing?
Figured out the solution. The tutorial neglected to mention that you also must add the line navBarControl1.ActiveGroupChanged += new DevExpress.XtraNavBar.NavBarGroupEventHandler(navBarControl1_ActiveGroupChanged); to Form1.cs in order to enable the user's changing of the active group to actually call the navBarControl1_ActiveGroupChanged function.

VLC.DotNet System.ComponentModel.Win32Exception: '%1 is not a valid Win32 application'

Working with:
Visual Studio 2017
NET framework 3.5
building for Any CPU
using 32-bit VLC version 2.2.6
using Vlc.DotNet (because i think it's only one that is working on any NET framework...)
I created new Form just for testing, how this library works (or if works)
used drag and drop method for "VlcControl" and one Button
All code is below:
Form.cs:
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "( *.mp4) | *.mp4"
};
if (ofd.ShowDialog() == DialogResult.OK)
{
vlcControl1.SetMedia(new FileInfo(Path.GetFileName(ofd.FileName)));
vlcControl1.Play();
}
}
}
}
Form.Designer.cs (Generated)
namespace WindowsFormsApp2
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.vlcControl1 = new Vlc.DotNet.Forms.VlcControl();
((System.ComponentModel.ISupportInitialize)(this.vlcControl1)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 255);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(260, 42);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// vlcControl1
//
this.vlcControl1.BackColor = System.Drawing.Color.Black;
this.vlcControl1.Location = new System.Drawing.Point(12, 12);
this.vlcControl1.Name = "vlcControl1";
this.vlcControl1.Size = new System.Drawing.Size(260, 237);
this.vlcControl1.Spu = -1;
this.vlcControl1.TabIndex = 2;
this.vlcControl1.Text = "vlcControl1";
this.vlcControl1.VlcLibDirectory = new System.IO.DirectoryInfo("C:\\Program Files (x86)\\VideoLAN\\VLC");
this.vlcControl1.VlcMediaplayerOptions = null;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 309);
this.Controls.Add(this.vlcControl1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.vlcControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private Vlc.DotNet.Forms.VlcControl vlcControl1;
}
}
Program.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Now the question is:
After calling "InitializeComponent()", program crashes:
In file: Form.Designer.cs
Line with:
((System.ComponentModel.ISupportInitialize)(this.vlcControl1)).EndInit();
throws System.ComponentModel.Win32Exception: '%1 is not a valid Win32 application'
How can i fix it???
Just set: Project-> Properties-> Build -> Platform Target = x86

How to use custom class with dynamic compilation

I have a form that i dynamicly compiled and i have a style class. When i copy this style class to my form source and compile it all works fine. But how can i use this style class without copy it to my form source. My main program that compile this form has this class, how can i use it? Maybe i can pass style class to this for with i compile it, like a var?
Program source:
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Microsoft.CSharp;
namespace dynamic
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(newForm).Start();
}
public void newForm()
{
using (CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string>
{
{"CompilerVersion", "v4.0"}
}))
{
var parameters = new CompilerParameters
{
GenerateExecutable = false, // Create a dll
GenerateInMemory = true, // Create it in memory
WarningLevel = 3, // Default warning level
CompilerOptions = "/optimize", // Optimize code
TreatWarningsAsErrors = false // Better be false to avoid break in warnings
};
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Data.dll");
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
parameters.ReferencedAssemblies.Add("System.Xml.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
var source = File.ReadAllText("form.txt");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, source);
Type type = results.CompiledAssembly.GetType("myForm.Form1");
object compiledObject = Activator.CreateInstance(type);
type.GetMethod("ShowDialog", new Type[0]).Invoke(compiledObject, new object[] {});
MessageBox.Show("formClosed");
}
}
}
}
Style folder:
Form source:
using System;
using System.Windows.Forms;
namespace myForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var newTmr = new Timer { Interval = 1000 };
newTmr.Tick += count;
newTmr.Enabled = true;
}
private void count(Object myObject, EventArgs myEventArgs)
{
timer.Value2 = (Int32.Parse(timer.Value2) + 1).ToString();
}
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("clicked");
}
private void nsButton1_Click(object sender, EventArgs e)
{
MessageBox.Show("button");
}
}
}
namespace myForm
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.nsTheme1 = new myForm.NSTheme();
this.nsButton1 = new myForm.NSButton();
this.timer = new myForm.NSLabel();
this.nsControlButton1 = new myForm.NSControlButton();
this.nsTheme1.SuspendLayout();
this.SuspendLayout();
//
// nsTheme1
//
this.nsTheme1.AccentOffset = 0;
this.nsTheme1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(50)))));
this.nsTheme1.BorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.nsTheme1.Colors = new myForm.Bloom[0];
this.nsTheme1.Controls.Add(this.nsControlButton1);
this.nsTheme1.Controls.Add(this.timer);
this.nsTheme1.Controls.Add(this.nsButton1);
this.nsTheme1.Customization = "";
this.nsTheme1.Dock = System.Windows.Forms.DockStyle.Fill;
this.nsTheme1.Font = new System.Drawing.Font("Verdana", 8F);
this.nsTheme1.Image = null;
this.nsTheme1.Location = new System.Drawing.Point(0, 0);
this.nsTheme1.Movable = true;
this.nsTheme1.Name = "nsTheme1";
this.nsTheme1.NoRounding = false;
this.nsTheme1.Sizable = true;
this.nsTheme1.Size = new System.Drawing.Size(284, 274);
this.nsTheme1.SmartBounds = true;
this.nsTheme1.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation;
this.nsTheme1.TabIndex = 0;
this.nsTheme1.Text = "nsTheme1";
this.nsTheme1.TransparencyKey = System.Drawing.Color.Empty;
this.nsTheme1.Transparent = false;
//
// nsButton1
//
this.nsButton1.Location = new System.Drawing.Point(100, 166);
this.nsButton1.Name = "nsButton1";
this.nsButton1.Size = new System.Drawing.Size(75, 23);
this.nsButton1.TabIndex = 0;
this.nsButton1.Text = "nsButton1";
this.nsButton1.Click += new System.EventHandler(this.nsButton1_Click);
//
// timer
//
this.timer.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Bold);
this.timer.Location = new System.Drawing.Point(91, 82);
this.timer.Name = "timer";
this.timer.Size = new System.Drawing.Size(101, 23);
this.timer.TabIndex = 1;
this.timer.Text = "nsLabel1";
this.timer.Value1 = "Timer: ";
this.timer.Value2 = "0";
//
// nsControlButton1
//
this.nsControlButton1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.nsControlButton1.ControlButton = myForm.NSControlButton.Button.Close;
this.nsControlButton1.Location = new System.Drawing.Point(262, 4);
this.nsControlButton1.Margin = new System.Windows.Forms.Padding(0);
this.nsControlButton1.MaximumSize = new System.Drawing.Size(18, 20);
this.nsControlButton1.MinimumSize = new System.Drawing.Size(18, 20);
this.nsControlButton1.Name = "nsControlButton1";
this.nsControlButton1.Size = new System.Drawing.Size(18, 20);
this.nsControlButton1.TabIndex = 2;
this.nsControlButton1.Text = "nsControlButton1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 274);
this.Controls.Add(this.nsTheme1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "Form1";
this.Text = "Form1";
this.nsTheme1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private NSTheme nsTheme1;
private NSButton nsButton1;
private NSControlButton nsControlButton1;
private NSLabel timer;
}
}
Style source:
http://pastebin.com/CjmQQ9ND
Project source - https://yadi.sk/d/ChtMacrsraD4g
If you compile this source, all will work fine. That because i use style at form.txt file. I separated form from style at form.txt file. I have this style at my main program (you can see that at screenshot). How can i send this style class to my dynamicly compiled form, so form can use it.
You should be able to simply append the style to the source like so:
var source = File.ReadAllText("form.txt");
source += Environment.NewLine;
source += File.ReadAllText("style.txt");
Inside Form.txt file instead of the classes in order prescribes the macro:
namespace myForm
{
<%THEME%>
}
namespace myForm
{
<%THEMEBASE%>
}
Before compile, load style files and replace them in the code form:
//Load style files
var NSThemeSource = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\..\Class\Style\NSTheme.cs"));
var themeBaseSource = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\..\Class\Style\ThemeBase154.cs"));
var source = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Form.txt"));
//Substitute in the form styles
source = source.Replace("<%THEME%>", NSThemeSource);
source = source.Replace("<%THEMEBASE%>", themeBaseSource);
P.S.
You can switch build action for style files at Embedded Resource so you can get style class from exe.
And use this helper - http://www.vcskicks.com/embedded-resource.php
Than you need to change code to:
var NSThemeSource = ResourceHelper.GetEmbeddedResource("Class/Style/NSTheme.cs");
var themeBaseSource = ResourceHelper.GetEmbeddedResource("Class/Style/ThemeBase154.cs");
First, you need to make classes, enums, and etc. public in NSTheme.cs and ThemeBase154.cs.
(it is better to put into some namespace, rather than having them in the global (dynamic) namespace).
Then, add parameters.ReferencedAssemblies.Add("dynamic.exe"); to you exe file (you might want to put your styles in a separate dll).
After it, in your form.txt add using dynamic; and remove qualifiers from new myForm.NSTheme() (so, it becomes new NSTheme()).
Now you can use your styles without coping them to your form class.
In case you miss something, check the CompilerResults results errors for particular problems.

JumpList in C# application (recent files)

At the moment I am developing an application and want to add a Windows (7) JumpList. I followed several tutorials and studied documentation, but I can't figure out how to get the job done. In short: I want a recent list of last choosen files. So after closing the app, the user can easily open a recent file with my application. I already implemented some file association mechanism.
Is it possible to share some code/ tutorial how I can solve above problem?
Thank you in advance!
*I already tried the next few projects/ tutorials:
http://www.codeproject.com/Articles/103913/How-to-Create-a-Custom-Jumplist-with-Custom-Events
http://channel9.msdn.com/coding4fun/articles/Windows-7-Jump-Lists
http://csharp-tricks-en.blogspot.nl/2011/10/create-jumplist-using-c.html
*The code of Coding 4 Fun works, but I don't know how to develop a recent file list.
You can check out this article. Instead of showing result in WPF you need to show it in jumplist.
Why dont you try storing the recently opened file names in a database or an xml file and read it to set the jumplist. For eg.
private void ReportUsage()
{
XmlDocument myXml = new XmlDocument();
myXml.Load(historyXml);
string list = historyXml;
jumpList.ClearAllUserTasks();
foreach (XmlElement el in myXml.DocumentElement.ChildNodes)
{
string s = el.GetAttribute("url");
JumpListLink jll = new JumpListLink(Assembly.GetEntryAssembly().Location, s);
jll.IconReference = new IconReference(Path.Combine("C:\\Program Files\\ACS Digital Media\\TOC WPF Browser\\Icon1.ico"), 0);
jll.Arguments = el.GetAttribute("url");
jumpList.AddUserTasks(jll);
}
jumpList.Refresh();
}
Or a beginners solution will be retain all the file paths into a Queue of given maximum capacity and adding them at run-time into a menuItem. Sorry I didnt have time to write the whole code.
As it is described in your second article, your application must be registered as a handler for targeted file extension, otherwise the recent category for your Jumplist won't show up. You can find more details about file association registration there.
You can either manually register your application but you will need admin right so it is not recommended, or create a setup project for your application like described in the coding 4 fun article, or you can let the user associate the file extension.
Here is a sample which works for me under Windows Seven without registration, by just right clicking the text file I want to load and choosing "Open With" and browse to my application.
The sample require Windows API Code Pack
public partial class Form1 : Form
{
[STAThread]
static void Main(string[] args)
{
var file = args != null && args.Length > 0 ? args[0] : string.Empty;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(file));
}
public Form1()
: this(string.Empty)
{
}
public Form1(string file)
{
InitializeComponent();
Open(file);
}
[DllImport("user32.dll")]
private static extern uint RegisterWindowMessage(string message);
private uint wmTBC;
/// <summary>
/// Registers the window message for notification when the taskbar button is created.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
wmTBC = RegisterWindowMessage("TaskbarButtonCreated");
}
/// <summary>
/// Handles the window message for notification of the taskbar button creation.
/// </summary>
/// <param name="m">The window message.</param>
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == wmTBC)
{
OnTaskbarButtonCreated();
}
}
/// <summary>
/// Override this method to recieve notification when the taskbar button is created on Windows 7 machines and above.
/// </summary>
protected void OnTaskbarButtonCreated()
{
if (TaskbarManager.IsPlatformSupported)
{
jumpList = JumpList.CreateJumpList();
jumpList.KnownCategoryToDisplay = JumpListKnownCategoryType.Recent;
jumpList.Refresh();
}
}
JumpList jumpList;
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
Open(ofd.FileName);
}
}
}
private void Open(string file)
{
try
{
if (!string.IsNullOrEmpty(file) && File.Exists(file))
{
textBox1.Text = File.ReadAllText(file);
if (TaskbarManager.IsPlatformSupported)
{
jumpList.AddToRecent(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 27);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(796, 306);
this.textBox1.TabIndex = 0;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(820, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem1});
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.openToolStripMenuItem.Text = "File";
//
// openToolStripMenuItem1
//
this.openToolStripMenuItem1.Name = "openToolStripMenuItem1";
this.openToolStripMenuItem1.Size = new System.Drawing.Size(152, 22);
this.openToolStripMenuItem1.Text = "Open";
this.openToolStripMenuItem1.Click += new System.EventHandler(this.openToolStripMenuItem1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(820, 345);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "Form1";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem1;
}

Categories

Resources