using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;

namespace Sample4_LaunchEXEFromMemory
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Label label1;
		private System.Windows.Forms.LinkLabel linkLabel1;
		private System.Windows.Forms.LinkLabel linkLabel2;
        private Button buttonLaunchExeFromMemory;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (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.label1 = new System.Windows.Forms.Label();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.linkLabel2 = new System.Windows.Forms.LinkLabel();
            this.buttonLaunchExeFromMemory = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(16, 8);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(488, 32);
            this.label1.TabIndex = 1;
            this.label1.Text = "This sample demonstrates how to create new process from a virtual file. For examp" +
                "le, from memory directly. Of course, no temporary file and drivers.";
            // 
            // linkLabel1
            // 
            this.linkLabel1.Location = new System.Drawing.Point(236, 125);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(168, 23);
            this.linkLabel1.TabIndex = 2;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "More about BoxedApp SDK";
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            // 
            // linkLabel2
            // 
            this.linkLabel2.Location = new System.Drawing.Point(420, 125);
            this.linkLabel2.Name = "linkLabel2";
            this.linkLabel2.Size = new System.Drawing.Size(80, 23);
            this.linkLabel2.TabIndex = 2;
            this.linkLabel2.TabStop = true;
            this.linkLabel2.Text = "Buy license";
            this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
            // 
            // buttonLaunchExeFromMemory
            // 
            this.buttonLaunchExeFromMemory.Location = new System.Drawing.Point(148, 55);
            this.buttonLaunchExeFromMemory.Name = "buttonLaunchExeFromMemory";
            this.buttonLaunchExeFromMemory.Size = new System.Drawing.Size(216, 52);
            this.buttonLaunchExeFromMemory.TabIndex = 3;
            this.buttonLaunchExeFromMemory.Text = "Launch EXE from memory";
            this.buttonLaunchExeFromMemory.UseVisualStyleBackColor = true;
            this.buttonLaunchExeFromMemory.Click += new System.EventHandler(this.buttonLaunchExeFromMemory_Click);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(512, 172);
            this.Controls.Add(this.buttonLaunchExeFromMemory);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.linkLabel2);
            this.Name = "Form1";
            this.Text = "Sample 4 - Launch EXE From Memory";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

		}
		#endregion

		[DllImport("kernel32.dll", SetLastError = true)]
		static extern bool CloseHandle(IntPtr hObject);

		[DllImport("kernel32.dll")]
		static extern bool WriteFile(IntPtr hFile, byte [] lpBuffer,
			uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten,
			[In] ref System.Threading.NativeOverlapped lpOverlapped);

        [DllImport("kernel32.dll")]
        static extern IntPtr LoadLibrary(string path);

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
        static extern IntPtr WinExec(string path, int nShowCmd);

		static void CreateVirtualEXE()
		{
            // We enable option DEF_BOXEDAPPSDK_OPTION__ALL_CHANGES_ARE_VIRTUAL
            // So all changes will be virtual
            // We can create new file, it will be created as a virtual file
            BoxedAppSDK.NativeMethods.BoxedAppSDK_EnableOption(BoxedAppSDK.NativeMethods.DEF_BOXEDAPPSDK_OPTION__ALL_CHANGES_ARE_VIRTUAL, true);

            using (Stream fs = new FileStream(@"virtual.exe", FileMode.CreateNew, FileAccess.Write))
            {
                Stream VirtualFileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Sample4_LaunchEXEFromMemory.EmbeddableApp.exe");
                byte[] buffer = new byte[VirtualFileStream.Length];
                VirtualFileStream.Read(buffer, 0, (int)VirtualFileStream.Length);
                fs.Write(buffer, 0, (int)VirtualFileStream.Length);
                fs.Close();
            }

            using (Stream fs = new FileStream(@"Dll1.dll", FileMode.CreateNew, FileAccess.Write))
            {
                Stream VirtualFileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Sample4_LaunchEXEFromMemory.Dll1.dll");
                byte[] buffer = new byte[VirtualFileStream.Length];
                VirtualFileStream.Read(buffer, 0, (int)VirtualFileStream.Length);
                fs.Write(buffer, 0, (int)VirtualFileStream.Length);
                fs.Close();
            }

            using (Stream fs = new FileStream(@"1.txt", FileMode.CreateNew, FileAccess.Write))
            {
                Stream VirtualFileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Sample4_LaunchEXEFromMemory.text_to_embed.txt");
                byte[] buffer = new byte[VirtualFileStream.Length];
                VirtualFileStream.Read(buffer, 0, (int)VirtualFileStream.Length);
                fs.Write(buffer, 0, (int)VirtualFileStream.Length);
                fs.Close();
            }

            // Disable option DEF_BOXEDAPPSDK_OPTION__ALL_CHANGES_ARE_VIRTUAL
            BoxedAppSDK.NativeMethods.BoxedAppSDK_EnableOption(BoxedAppSDK.NativeMethods.DEF_BOXEDAPPSDK_OPTION__ALL_CHANGES_ARE_VIRTUAL, false);
		}

        /// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			BoxedAppSDK.NativeMethods.BoxedAppSDK_Init();

            CreateVirtualEXE();

			Application.Run(new Form1());
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
		}

		private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
		{
			System.Diagnostics.Process.Start("http://www.boxedapp.com/?from_program=1");
		}

		private void linkLabel2_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
		{
			System.Diagnostics.Process.Start("http://www.boxedapp.com/order.html?from_program=1");
		}

        private void buttonLaunchExeFromMemory_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("virtual.exe", "1.txt");
        }
	}
}
