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 Sample1_FlashActiveXEmbedding
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private AxShockwaveFlashObjects.AxShockwaveFlash axShockwaveFlash1;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.LinkLabel linkLabel1;
		private System.Windows.Forms.LinkLabel linkLabel2;
		/// <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()
		{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.axShockwaveFlash1 = new AxShockwaveFlashObjects.AxShockwaveFlash();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.linkLabel2 = new System.Windows.Forms.LinkLabel();
            ((System.ComponentModel.ISupportInitialize)(this.axShockwaveFlash1)).BeginInit();
            this.SuspendLayout();
            // 
            // axShockwaveFlash1
            // 
            this.axShockwaveFlash1.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.axShockwaveFlash1.Enabled = true;
            this.axShockwaveFlash1.Location = new System.Drawing.Point(8, 136);
            this.axShockwaveFlash1.Name = "axShockwaveFlash1";
            this.axShockwaveFlash1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axShockwaveFlash1.OcxState")));
            this.axShockwaveFlash1.Size = new System.Drawing.Size(496, 344);
            this.axShockwaveFlash1.TabIndex = 0;
            // 
            // 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 embed Flash ActiveX Control into application. Als" +
                "o it demonstrates how to load a flash movie from memory.";
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(16, 48);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(488, 32);
            this.label2.TabIndex = 1;
            this.label2.Text = "Flash ActiveX is not able to load movie from memory, BoxedApp SDK is a solution! " +
                "You just create a new virtual file with a movie and pass it to Flash ActiveX. Th" +
                "at\'s all.";
            // 
            // linkLabel1
            // 
            this.linkLabel1.Location = new System.Drawing.Point(16, 88);
            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(200, 88);
            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);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(512, 494);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.axShockwaveFlash1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.linkLabel2);
            this.Name = "Form1";
            this.Text = "Sample 1 - FlashActiveXEmbedding";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.axShockwaveFlash1)).EndInit();
            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);

		static void InstallFlashOCXInVirtualRegistry()
		{
            // 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);

            Stream fs = new FileStream(@"flash.ocx", FileMode.CreateNew, FileAccess.Write);
            Stream VirtualFileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Sample1_FlashActiveXEmbedding.Flash.ocx");
            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);

            // Register virtual file "Flash.ocx" in virtual registry
            BoxedAppSDK.NativeMethods.BoxedAppSDK_RegisterCOMLibraryInVirtualRegistry(@"Flash.ocx");

            // Another idea:
            /*
			using (SafeFilehandle hHandle1 = 
                new SafeFileHandle(
				    BoxedAppSDK.NativeMethods.BoxedAppSDK_CreateVirtualFile(
				        @"C:\Flash.ocx", 
				        BoxedAppSDK.NativeMethods.EFileAccess.GenericWrite, 
				        BoxedAppSDK.NativeMethods.EFileShare.Read, 
				        IntPtr.Zero, 
				        BoxedAppSDK.NativeMethods.ECreationDisposition.New, 
				        BoxedAppSDK.NativeMethods.EFileAttributes.Normal, 
				        IntPtr.Zero
                    ),
                    true
                )
            )
            {
			    Stream VirtualFileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Sample1_FlashActiveXEmbedding.Flash.ocx");

			    byte[] Buffer = new byte[VirtualFileStream.Length];
			    VirtualFileStream.Read(Buffer, 0, Buffer.Length);

			    uint NumberOfBytesWritten;
			    System.Threading.NativeOverlapped Overlapped = new System.Threading.NativeOverlapped();
			    WriteFile(hHandle1, Buffer, (uint)Buffer.Length, out NumberOfBytesWritten, ref Overlapped);
            }

			BoxedAppSDK.NativeMethods.BoxedAppSDK_RegisterCOMLibraryInVirtualRegistry(@"C:\Flash.ocx");
            */
		}

        static string _strFlashMoviePath = 
            System.IO.Path.GetDirectoryName(Application.ExecutablePath) + @"\movie.swf";

		static void CreateVirtualFlashFile()
		{
            // 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);

            Stream fs = new FileStream(_strFlashMoviePath, FileMode.CreateNew, FileAccess.Write);
            Stream VirtualFileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Sample1_FlashActiveXEmbedding.movie.swf");
            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);

            // Another idea:
            /*
            using(SafeFileHandle hHandle =
                new SafeFileHandle(
                    BoxedAppSDK.NativeMethods.BoxedAppSDK_CreateVirtualFile(
                        _strFlashMoviePath,
                        BoxedAppSDK.NativeMethods.EFileAccess.GenericWrite,
                        BoxedAppSDK.NativeMethods.EFileShare.Read,
                        IntPtr.Zero,
                        BoxedAppSDK.NativeMethods.ECreationDisposition.New,
                        BoxedAppSDK.NativeMethods.EFileAttributes.Normal,
                        IntPtr.Zero
                    ),
                    true
                )
            )
            {
                Stream VirtualFileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Sample1_FlashActiveXEmbedding.movie.swf");

                byte[] Buffer = new byte[VirtualFileStream.Length];
                VirtualFileStream.Read(Buffer, 0, Buffer.Length);

                System.Threading.NativeOverlapped Overlapped = new System.Threading.NativeOverlapped();
                uint NumberOfBytesWritten;
                WriteFile(hHandle, Buffer, (uint)Buffer.Length, out NumberOfBytesWritten, ref Overlapped);
            }
            */
        }

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

			InstallFlashOCXInVirtualRegistry();
			CreateVirtualFlashFile();

			Application.Run(new Form1());
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
            axShockwaveFlash1.Movie = _strFlashMoviePath;
		}

		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");
		}
	}
}
