Exemple #1
0
        public static UIElement Load(IconResource resource)
        {
            try
            {
                switch (resource)
                {
                case BitmapIconResource bitmap:
                    return(LoadBitmapResource(bitmap));

                case EmbeddedIconResource embedded:
                    return(LoadEmbeddedResource(embedded));

                case NativeIconResource native:
                    return(LoadNativeResource(native));

                case XamlIconResource xaml:
                    return(LoadXamlResource(xaml));

                default:
                    throw new NotSupportedException($"Application icon resource of type '{resource.GetType()}' is not supported!");
                }
            }
            catch (Exception)
            {
                return(NotFoundSymbol());
            }
        }
    public static GroupIconResource FromByteArray(byte[] GroupData, ModuleResourceLibary Module)
    {
        if (GroupData != null)
        {
            using (MemoryStream Input = new MemoryStream(GroupData))
            {
                BinaryReader Reader = new BinaryReader(Input);

                Reader.ReadUInt16(); // Reserved
                Reader.ReadUInt16(); // Type
                ushort Count = Reader.ReadUInt16();

                IconResource[] Icons = new IconResource[Count];
                for (int Idx = 0; Idx < Count; Idx++)
                {
                    Icons[Idx] = ReadIconHeader(Reader);
                    int IconId = Reader.ReadUInt16();
                    Icons[Idx].Data = Module.ReadResource(IconId, ResourceType.Icon);
                }
                return new GroupIconResource(Icons);
            }
        }
        else
        {
            return null;
        }
    }
        public void PersistentIconResources()
        {
            // Load dummy.
            var image = PEImage.FromBytes(Properties.Resources.HelloWorld);

            // Update icon resources.
            var iconResource = IconResource.FromDirectory(image.Resources);

            foreach (var iconGroup in iconResource.GetIconGroups())
            {
                iconGroup.RemoveEntry(4);
                iconGroup.Count--;
            }
            iconResource.WriteToDirectory(image.Resources);

            // Rebuild.
            using var stream = new MemoryStream();
            new ManagedPEFileBuilder().CreateFile(image).Write(new BinaryStreamWriter(stream));

            // Reload version info.
            var newImage        = PEImage.FromBytes(stream.ToArray());
            var newIconResource = IconResource.FromDirectory(newImage.Resources);

            // Verify.
            Assert.Equal(iconResource.GetIconGroups().ToList()[0].Count, newIconResource.GetIconGroups().ToList()[0].Count);
        }
 public AboutNotificationInfo(IText text)
 {
     IconResource = new XamlIconResource {
         Uri = new Uri("pack://application:,,,/SafeExamBrowser.UserInterface.Desktop;component/Images/AboutNotification.xaml")
     };
     Tooltip = text.Get(TextKey.Notification_AboutTooltip);
 }
	public static GroupIconResource FromIco(string FileName)
	{
		using(FileStream Stream = new FileStream(FileName, FileMode.Open, FileAccess.Read))
		{
			BinaryReader Reader = new BinaryReader(Stream);

			Reader.ReadUInt16(); // Reserved
			Reader.ReadUInt16(); // Type
			ushort Count = Reader.ReadUInt16();

			IconResource[] Icons = new IconResource[Count];
			uint[] Offsets = new uint[Count];

			for(int Idx = 0; Idx < Count; Idx++)
			{
				Icons[Idx] = ReadIconHeader(Reader);
				Offsets[Idx] = Reader.ReadUInt32();
			}

			for(int Idx = 0; Idx < Icons.Length; Idx++)
			{
				Stream.Seek(Offsets[Idx], SeekOrigin.Begin);
				Stream.Read(Icons[Idx].Data, 0, Icons[Idx].Data.Length);
			}

			return new GroupIconResource(Icons);
		}
	}
 public LogNotificationInfo(IText text)
 {
     IconResource = new BitmapIconResource {
         Uri = new Uri("pack://application:,,,/SafeExamBrowser.UserInterface.Desktop;component/Images/LogNotification.ico")
     };
     Tooltip = text.Get(TextKey.Notification_LogTooltip);
 }
Exemple #7
0
    public static GroupIconResource FromIco(string FileName)
    {
        using (FileStream Stream = new FileStream(FileName, FileMode.Open, FileAccess.Read))
        {
            BinaryReader Reader = new BinaryReader(Stream);

            Reader.ReadUInt16();             // Reserved
            Reader.ReadUInt16();             // Type
            ushort Count = Reader.ReadUInt16();

            IconResource[] Icons   = new IconResource[Count];
            uint[]         Offsets = new uint[Count];

            for (int Idx = 0; Idx < Count; Idx++)
            {
                Icons[Idx]   = ReadIconHeader(Reader);
                Offsets[Idx] = Reader.ReadUInt32();
            }

            for (int Idx = 0; Idx < Icons.Length; Idx++)
            {
                Stream.Seek(Offsets[Idx], SeekOrigin.Begin);
                Stream.Read(Icons[Idx].Data, 0, Icons[Idx].Data.Length);
            }

            return(new GroupIconResource(Icons));
        }
    }
Exemple #8
0
    public static GroupIconResource FromByteArray(byte[] GroupData, ModuleResourceLibary Module)
    {
        if (GroupData != null)
        {
            using (MemoryStream Input = new MemoryStream(GroupData))
            {
                BinaryReader Reader = new BinaryReader(Input);

                Reader.ReadUInt16();                 // Reserved
                Reader.ReadUInt16();                 // Type
                ushort Count = Reader.ReadUInt16();

                IconResource[] Icons = new IconResource[Count];
                for (int Idx = 0; Idx < Count; Idx++)
                {
                    Icons[Idx] = ReadIconHeader(Reader);
                    int IconId = Reader.ReadUInt16();
                    Icons[Idx].Data = Module.ReadResource(IconId, ResourceType.Icon);
                }
                return(new GroupIconResource(Icons));
            }
        }
        else
        {
            return(null);
        }
    }
        private Image AddIcon(AnnotateIcon annotateIcon, AnnotateIconSize annotateIconSize)
        {
            var img = IconResource.ExtractAnnotationIcon(annotateIcon, annotateIconSize);

            if (img == null)
            {
                var assembly = Assembly.LoadFrom(@"Atalasoft.dotImage.dll");
                if (assembly != null)
                {
                    var stream = assembly.GetManifestResourceStream("Atalasoft.Imaging.Annotate.Icons._" + annotateIconSize.ToString().Substring(4) + "." + annotateIcon + ".png");
                    img = Image.FromStream(stream);
                }

                if (img == null)
                {
                    if (annotateIconSize.ToString() == "size16")
                    {
                        return(new AtalaImage(16, 16, PixelFormat.Pixel24bppBgr, Color.White).ToBitmap());
                    }
                    if (annotateIconSize.ToString() == "size24")
                    {
                        return(new AtalaImage(24, 24, PixelFormat.Pixel24bppBgr, Color.White).ToBitmap());
                    }
                    if (annotateIconSize.ToString() == "size32")
                    {
                        return(new AtalaImage(32, 32, PixelFormat.Pixel24bppBgr, Color.White).ToBitmap());
                    }
                }
            }

            return(img);
        }
Exemple #10
0
        private BitmapSource ExtractAnnotationIcon(AnnotateIcon icon, AnnotateIconSize size)
        {
            BitmapSource returnSource = WpfObjectConverter.ConvertBitmap((Bitmap)IconResource.ExtractAnnotationIcon(icon, size));

            if (returnSource == null)
            {
                Assembly assm = Assembly.LoadFrom(@"Atalasoft.dotImage.dll");
                if (assm != null)
                {
                    Stream stream = assm.GetManifestResourceStream("Atalasoft.Imaging.Annotate.Icons._" + size.ToString().Substring(4) + "." + icon.ToString() + ".png");
                    returnSource = WpfObjectConverter.ConvertBitmap((Bitmap)System.Drawing.Image.FromStream(stream));
                }

                // if it's STILL null, then give up and make placeholders
                if (returnSource == null)
                {
                    switch (size.ToString())
                    {
                    case "size16":
                        returnSource = WpfObjectConverter.ConvertBitmap(new AtalaImage(16, 16, PixelFormat.Pixel24bppBgr, System.Drawing.Color.White).ToBitmap());
                        break;

                    case "size24":
                        returnSource = WpfObjectConverter.ConvertBitmap(new AtalaImage(24, 24, PixelFormat.Pixel24bppBgr, System.Drawing.Color.White).ToBitmap());
                        break;

                    case "size32":
                        returnSource = WpfObjectConverter.ConvertBitmap(new AtalaImage(32, 32, PixelFormat.Pixel24bppBgr, System.Drawing.Color.White).ToBitmap());
                        break;
                    }
                }
            }

            return(returnSource);
        }
        private void InitializeAudioControl()
        {
            var originalBrush = Grid.Background;

            audio.VolumeChanged += Audio_VolumeChanged;
            Button.Click        += (o, args) => Popup.IsOpen = !Popup.IsOpen;
            Button.MouseLeave   += (o, args) => Task.Delay(250).ContinueWith(_ => Dispatcher.Invoke(() => Popup.IsOpen = Popup.IsMouseOver));
            MuteButton.Click    += MuteButton_Click;
            MutedIcon            = new XamlIconResource {
                Uri = new Uri("pack://application:,,,/SafeExamBrowser.UserInterface.Mobile;component/Images/Audio_Muted.xaml")
            };
            NoDeviceIcon = new XamlIconResource {
                Uri = new Uri("pack://application:,,,/SafeExamBrowser.UserInterface.Mobile;component/Images/Audio_Light_NoDevice.xaml")
            };
            Popup.MouseLeave    += (o, args) => Task.Delay(250).ContinueWith(_ => Dispatcher.Invoke(() => Popup.IsOpen = IsMouseOver));
            Popup.Opened        += (o, args) => Grid.Background = Brushes.Gray;
            Popup.Closed        += (o, args) => Grid.Background = originalBrush;
            Volume.ValueChanged += Volume_ValueChanged;

            if (audio.HasOutputDevice)
            {
                AudioDeviceName.Text = audio.DeviceFullName;
                Button.IsEnabled     = true;
                UpdateVolume(audio.OutputVolume, audio.OutputMuted);
            }
            else
            {
                AudioDeviceName.Text = text.Get(TextKey.SystemControl_AudioDeviceNotFound);
                Button.IsEnabled     = false;
                Button.ToolTip       = text.Get(TextKey.SystemControl_AudioDeviceNotFound);
                ButtonIcon.Content   = IconResourceLoader.Load(NoDeviceIcon);
            }
        }
Exemple #12
0
 internal ExternalApplicationInstance(IconResource icon, ILogger logger, INativeMethods nativeMethods, IProcess process)
 {
     this.icon          = icon;
     this.logger        = logger;
     this.nativeMethods = nativeMethods;
     this.process       = process;
     this.windows       = new List <ExternalApplicationWindow>();
 }
Exemple #13
0
 public void WriteIconHeader(BinaryWriter Writer, IconResource Icon)
 {
     Writer.Write(Icon.Width);
     Writer.Write(Icon.Height);
     Writer.Write(Icon.ColorCount);
     Writer.Write((byte)0);
     Writer.Write(Icon.Planes);
     Writer.Write(Icon.BitCount);
     Writer.Write(Icon.Data.Length);
 }
        public AboutNotification(AppConfig appConfig, IText text, IUserInterfaceFactory uiFactory)
        {
            this.appConfig = appConfig;
            this.text      = text;
            this.uiFactory = uiFactory;

            IconResource = new XamlIconResource {
                Uri = new Uri("pack://application:,,,/SafeExamBrowser.UserInterface.Desktop;component/Images/AboutNotification.xaml")
            };
            Tooltip = text.Get(TextKey.Notification_AboutTooltip);
        }
Exemple #15
0
        public LogNotification(ILogger logger, IText text, IUserInterfaceFactory uiFactory)
        {
            this.logger    = logger;
            this.text      = text;
            this.uiFactory = uiFactory;

            IconResource = new BitmapIconResource {
                Uri = new Uri("pack://application:,,,/SafeExamBrowser.UserInterface.Desktop;component/Images/LogNotification.ico")
            };
            Tooltip = text.Get(TextKey.Notification_LogTooltip);
        }
        public void ReadIconGroupResourceDirectory()
        {
            // Load dummy.
            var image = PEImage.FromBytes(Properties.Resources.HelloWorld);

            // Read icon resources.
            var iconResource = IconResource.FromDirectory(image.Resources);

            // Verify.
            Assert.Single(iconResource.GetIconGroups());
            Assert.Equal(4, iconResource.GetIconGroups().ToList()[0].GetIconEntries().Count());
        }
Exemple #17
0
 private void LoadImage(string path, IconResource key)
 {
     try
     {
         var bmp = new BitmapImage(new Uri(path, UriKind.Relative));
         Icons.Add(key, bmp);
     }
     catch (Exception e)
     {
         Debug.WriteLine($"画像リソース {path}の読み込みに失敗しました");
         Debug.WriteLine(e.Message);
         Icons.Add(key, CreateBlankImage());
     }
 }
Exemple #18
0
        private static void LoadResource(int resId)
        {
            Resource tempRes = ResourceFactory.Inst.LoadResource(resId, (res) =>
            {
                if (null == res)
                {
                    Debug.LogError("图片资源为空:" + resId);
                    return;
                }
                IconResource iconRes = res as IconResource;
                if (null == iconRes)
                {
                    Debug.LogError(resId + "动态图片加载失败,类型错误 !");
                    return;
                }

                Texture tex = iconRes.GetTexture();
                TextureManager.m_dicTexure.Add(resId, tex);

                List <RawImage> list = TextureManager.m_listLoading[resId];
                for (int i = 0; i < list.Count; i++)
                {
                    if (null == list[i])
                    {
                        continue;
                    }
                    list[i].enabled = true;
                    list[i].texture = tex;
                }
                list.Clear();
                list = null;
                TextureManager.m_listLoading.Remove(resId);
            });

            m_listRes.Add(tempRes);
        }
        private void updateMainResource()
        {
            string filenameDownloader  = WorkingDir + DownloaderFileName;
            string filenameSatelliteRC = WorkingDir + constDownloaderSatelliteResource;

            ResourceInfo rcInfo = new ResourceInfo();

            rcInfo.Load(filenameDownloader);
            rcInfo.Unload(); // Release the module so its can be saved
            // Begin the batch update to the designated module to speed up the process
            ResourceInfo.BeginBatchUpdate(filenameDownloader);
            try
            {
                // ==========================
                // Modify the Icon
                // ==========================
                // Look up the ICON resource
                if (IconFullPath.Trim() != "")
                {
                    msResIdToFind = 128;
                    IconDirectoryResource icoRC = (IconDirectoryResource)rcInfo[Kernel32.ResourceTypes.RT_GROUP_ICON].Find(FindRes);
                    if (icoRC == null)
                    {
                        throw new ApplicationException(AppResource.ResIcon128NotFound);
                    }

                    IconFile icoFile = new IconFile(IconFullPath.Trim());
                    uint     j       = 1;
                    icoRC.Icons.RemoveRange(0, icoRC.Icons.Count);
                    icoRC.SaveTo(filenameDownloader);
                    foreach (IconFileIcon icoFileIcon in icoFile.Icons)
                    {
                        IconResource icoRes = new IconResource(icoFileIcon, new ResourceId(j), 1033);
                        icoRes.Name = new ResourceId(j++);
                        icoRC.Icons.Add(icoRes);
                    }
                    icoRC.SaveTo(filenameDownloader);
                }
                // ==================================
                // Modify the strings in the resource
                // ==================================
                // Downloader GUID
                StringResource stringRC = null;
                msResIdToFind = StringResource.GetBlockId(40401);
                stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                if (stringRC == null)
                {
                    throw new ApplicationException(
                              string.Format(AppResource.ResStringTemplateNotFound, 40401));
                }

                stringRC.Strings[40401] = string.Format(stringRC.Strings[40401], DownloaderGuid);
                stringRC.SaveTo(filenameDownloader);
                // ==========================================================
                // Embed the modified satellite resource into the main resource
                // ==========================================================
                // Look up the embedded satellite resource
                msResIdToFind = 1000;
                GenericResource satelliteRC = (GenericResource)rcInfo.Resources[new ResourceId(1001)].Find(FindRes);
                if (satelliteRC == null)
                {
                    throw new ApplicationException(
                              AppResource.ResEmbededSatelliteDllNotFound);
                }

                // Compresse the satellite RC file.
                MemoryStream memStream = new MemoryStream(1024 * 10);
                FileStream   fs        = new FileStream(
                    filenameSatelliteRC,
                    FileMode.Open);
                byte[] temp = new byte[fs.Length];
                fs.Read(temp, 0, temp.Length);
                fs.Close();
                using (GZipStream Compress = new GZipStream(memStream, CompressionMode.Compress))
                {
                    // Compress the data into the memory stream
                    Compress.Write(temp, 0, temp.Length);
                    // Read the compressed data from the memory stream
                    temp = new byte[memStream.Length + 1];
                    memStream.Position = 0;
                    // Leave the 1st byte as cheating byte and start to fill the array from the 2nd byte
                    for (long i = 1; i < memStream.Length + 1; i++)
                    {
                        temp[i] = Convert.ToByte(memStream.ReadByte());
                    }
                }
                memStream.Close();
                satelliteRC.Data = temp;
                satelliteRC.SaveTo(filenameDownloader);
                // Erease the english satellite resource since it has been used to overwrite the main satellite resource!!
                // Or it will remain useless if its choose to generate the chinese downloader!
                msResIdToFind = 1002;
                satelliteRC   = (GenericResource)rcInfo.Resources[new ResourceId(1001)].Find(FindRes);
                if (satelliteRC == null)
                {
                    throw new ApplicationException(
                              AppResource.ResEmbededSatelliteDllNotFound);
                }
                // The binary array must contain at least one element to prevent the failure in some cases
                satelliteRC.Data = new byte[1];
                satelliteRC.SaveTo(filenameDownloader);
            }
            catch (Exception oEx)
            {
                throw oEx;
            }
            finally
            {
                // Commit the batch updates to the module
                ResourceInfo.EndBatchUpdate();
            }
        }
        private void updateResource()
        {
            string filenameDownloader = WorkingDir + DownloaderFileName;
            string filenameDownloaderSatelliteResource = WorkingDir + constDownloaderSatelliteResource;

            // Look up the satellite resource
            ResourceInfo rcInfo = new ResourceInfo();

            rcInfo.Load(filenameDownloader);
            rcInfo.Unload(); // Release the module so its can be saved

            // Chinese Satellite Resource
            msResIdToFind = 1000;
            if (AppResource.Culture.Name == "en-US")
            {
                // English Satellite Resource
                msResIdToFind = 1002;
            }

            GenericResource satelliteRC = (GenericResource)rcInfo.Resources[new ResourceId(1001)].Find(FindRes);

            byte[]       temp         = satelliteRC.WriteAndGetBytes();
            MemoryStream memSatellite = new MemoryStream(1024 * 10);

            memSatellite.Write(temp, 0, temp.Length);
            memSatellite.Position = 0;
            //Create the decompressed file.
            using (FileStream fileSatellite = File.Create(filenameDownloaderSatelliteResource))
            {
                using (GZipStream Decompress = new GZipStream(memSatellite, CompressionMode.Decompress))
                {
                    readWriteStream(Decompress, fileSatellite);
                }
            }
            // Load the satellite resource
            rcInfo = new ResourceInfo();
            rcInfo.Load(filenameDownloaderSatelliteResource);
            rcInfo.Unload(); // Release the module so its can be saved
            // Begin the batch update to the designated module to speed up the process
            ResourceInfo.BeginBatchUpdate(filenameDownloaderSatelliteResource);
            try
            {
                // ==========================
                // Modify the Banner
                // ==========================
                // Look up the bitmap resource
                if (BannerBitmapFullPath.Trim() != "")
                {
                    msResIdToFind = 207;
                    BitmapResource bmpRC = (BitmapResource)rcInfo[Kernel32.ResourceTypes.RT_BITMAP].Find(FindRes);
                    if (bmpRC == null)
                    {
                        throw new ApplicationException(
                                  AppResource.ResBitmap207NotFound);
                    }

                    BitmapFile bmpFile = new BitmapFile(BannerBitmapFullPath.Trim());
                    bmpRC.Bitmap = bmpFile.Bitmap;
                    bmpRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // ==========================
                // Modify the Icon
                // ==========================
                // Look up the ICON resource
                if (IconFullPath.Trim() != "")
                {
                    msResIdToFind = 128;
                    IconDirectoryResource icoRC = (IconDirectoryResource)rcInfo[Kernel32.ResourceTypes.RT_GROUP_ICON].Find(FindRes);
                    if (icoRC == null)
                    {
                        throw new ApplicationException(AppResource.ResIcon128NotFound);
                    }

                    IconFile icoFile = new IconFile(IconFullPath.Trim());
                    uint     j       = 1;
                    icoRC.Icons.RemoveRange(0, icoRC.Icons.Count);
                    icoRC.SaveTo(filenameDownloaderSatelliteResource);
                    foreach (IconFileIcon icoFileIcon in icoFile.Icons)
                    {
                        IconResource icoRes = new IconResource(icoFileIcon, new ResourceId(j), 1033);
                        icoRes.Name = new ResourceId(j++);
                        icoRC.Icons.Add(icoRes);
                    }
                    icoRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // ==========================
                // Modify the main dialog box
                // ==========================
                // Look up the dialog resource
                msResIdToFind = 201;
                DialogResource dlgRC = (DialogResource)rcInfo[Kernel32.ResourceTypes.RT_DIALOG].Find(FindRes);
                if (dlgRC == null)
                {
                    throw new ApplicationException(AppResource.ResDialog201NotFound);
                }

                // Find the designated label control
                msCtrlIdToFind = 1010;
                DialogTemplateControlBase ctrl = dlgRC.Template.Controls.Find(FindDlgControl);
                ctrl.CaptionId.Name = string.Format(ctrl.CaptionId.Name, DownloaderDisplayName);
                // Find the designated link control
                msCtrlIdToFind      = 1006;
                ctrl                = dlgRC.Template.Controls.Find(FindDlgControl);
                ctrl.CaptionId.Name = string.Format(ctrl.CaptionId.Name, DownloaderHomeUrl);
                dlgRC.SaveTo(filenameDownloaderSatelliteResource);
                // ===================================================
                // Embed the specified .Torrent file into the resource
                // ===================================================
                // Look up the torrent resource
                msResIdToFind = 1021;
                GenericResource torrentRC = (GenericResource)rcInfo.Resources[new ResourceId(1022)].Find(FindRes);
                if (torrentRC == null)
                {
                    throw new ApplicationException(AppResource.ResTorrentSlot2011NotFound);
                }

                FileStream fs = new FileStream(MetafileFullPath, FileMode.Open);
                temp = new byte[fs.Length];
                fs.Read(temp, 0, temp.Length);
                fs.Close();
                torrentRC.Data = temp;
                torrentRC.SaveTo(filenameDownloaderSatelliteResource);
                // ===================================================
                // Embed the specified disclaimer file into the resource
                // ===================================================
                // Look up the disclaimer resource
                if (DisclaimerFullPath.Trim() != "")
                {
                    msResIdToFind = 40111;
                    GenericResource disclaimerRC = (GenericResource)rcInfo.Resources[new ResourceId(40112)].Find(FindRes);
                    if (disclaimerRC == null)
                    {
                        throw new ApplicationException(AppResource.ResDisclaimerSlot40112NotFound);
                    }

                    fs   = new FileStream(DisclaimerFullPath.Trim(), FileMode.Open);
                    temp = new byte[fs.Length];
                    fs.Read(temp, 0, temp.Length);
                    fs.Close();
                    disclaimerRC.Data = temp;
                    disclaimerRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // ==================================
                // Modify the strings in the resource
                // ==================================
                // Display Name
                StringResource stringRC = null;
                int[]          stringID = new int[] { 1112, 13015, 13016, 13017, 13018, 13019, 13027 };
                for (int i = 0; i < stringID.Length; i++)
                {
                    int sID = stringID[i];
                    // Check if the string resource has been loaded in the last string block or not.
                    if (stringRC == null || !stringRC.Strings.ContainsKey((ushort)sID))
                    {
                        msResIdToFind = StringResource.GetBlockId(sID);
                        stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                        if (stringRC == null)
                        {
                            throw new ApplicationException(
                                      string.Format(AppResource.ResStringTemplateNotFound, sID));
                        }
                    }
                    stringRC.Strings[(ushort)sID] = string.Format(stringRC.Strings[(ushort)sID], DownloaderDisplayName);
                    // Leave the modified string resource unsaved until all the strings in the string block are done.
                    if (stringID.Length == (i + 1) || !stringRC.Strings.ContainsKey((ushort)stringID[i + 1]))
                    {
                        stringRC.SaveTo(filenameDownloaderSatelliteResource);
                    }
                }
                // Google Analytics Profile ID
                msResIdToFind = StringResource.GetBlockId(1113);
                stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                if (stringRC == null)
                {
                    throw new ApplicationException(
                              string.Format(AppResource.ResStringTemplateNotFound, 1113));
                }

                stringRC.Strings[1113] = string.Format(stringRC.Strings[1113], GoogleAnalyticsProfileID);
                stringRC.SaveTo(filenameDownloaderSatelliteResource);
                // Downloader GUID
                msResIdToFind = StringResource.GetBlockId(40401);
                stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                if (stringRC == null)
                {
                    throw new ApplicationException(
                              string.Format(AppResource.ResStringTemplateNotFound, 40401));
                }

                stringRC.Strings[40401] = string.Format(stringRC.Strings[40401], DownloaderGuid);
                stringRC.SaveTo(filenameDownloaderSatelliteResource);
                // Online FAQ URL
                if (OnlineFaqUrl.Trim() != "")
                {
                    msResIdToFind = StringResource.GetBlockId(13020);
                    stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                    if (stringRC == null)
                    {
                        throw new ApplicationException(
                                  string.Format(AppResource.ResStringTemplateNotFound, 13020));
                    }

                    stringRC.Strings[13020] = OnlineFaqUrl;
                    stringRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // Event ID
                if (PromotionEventID.Trim() != "")
                {
                    msResIdToFind = StringResource.GetBlockId(1104);
                    stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                    if (stringRC == null)
                    {
                        throw new ApplicationException(
                                  string.Format(AppResource.ResStringTemplateNotFound, 1104));
                    }

                    stringRC.Strings[1104] = string.Format(stringRC.Strings[1104], PromotionEventID);
                    stringRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // Event Server URL
                if (PromotionEventID.Trim() != "")
                {
                    msResIdToFind = StringResource.GetBlockId(1101);
                    stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                    if (stringRC == null)
                    {
                        throw new ApplicationException(
                                  string.Format(AppResource.ResStringTemplateNotFound, 1101));
                    }

                    // Conver the URL to base64 encoded string
                    stringRC.Strings[1101] = Convert.ToBase64String(Encoding.ASCII.GetBytes(PromotionEventServerUrl));
                    stringRC.SaveTo(filenameDownloaderSatelliteResource);
                }
            }
            catch (Exception oEx)
            {
                throw oEx;
            }
            finally
            {
                // Commit the batch updates to the module
                ResourceInfo.EndBatchUpdate();
            }
        }
Exemple #21
0
        private void BtnCreateMod_Click(object sender, EventArgs e)
        {
            if (cbCreateSFX.Checked)
            {
                saveFileDlg.FilterIndex = 1;
            }
            else
            {
                saveFileDlg.FilterIndex = 2;
            }
            if (saveFileDlg.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            try
            {
                File.Delete(saveFileDlg.FileName);
                AAPak  modpak          = new AAPak(saveFileDlg.FileName, false, true);
                Bitmap customIconImage = null;

                // First check image we will use (if any)
                if (useDefaultImage)
                {
                    MemoryStream iconStream = new MemoryStream();
                    Properties.Resources.mod_example_icon.Save(iconStream, System.Drawing.Imaging.ImageFormat.Png);

                    /*
                     * if (!modpak.AddFileFromStream(ModPNGImageFileName, iconStream, DateTime.Now, DateTime.Now, false, out _))
                     * {
                     *  MessageBox.Show("Failed to add default icon");
                     *  modpak.ClosePak();
                     *  return;
                     * }
                     */
                    customIconImage = new Bitmap(Properties.Resources.mod_example_icon.GetThumbnailImage(128, 128, null, new IntPtr()));
                }
                else
                if (NewCustomImage != string.Empty)
                {
                    FileStream iconStream = File.Open(NewCustomImage, FileMode.Open, FileAccess.Read, FileShare.Read);

                    /*
                     * if ( (Path.GetExtension(NewCustomImage).ToLower() == ".png") && (!modpak.AddFileFromStream(ModPNGImageFileName, iconStream, DateTime.Now, DateTime.Now, false, out _)) )
                     * {
                     *  MessageBox.Show("Failed to add PNG icon");
                     *  modpak.ClosePak();
                     *  return;
                     * }
                     * else
                     * if ((Path.GetExtension(NewCustomImage).ToLower() == ".jpg") && (!modpak.AddFileFromStream(ModJPGImageFileName, iconStream, DateTime.Now, DateTime.Now, false, out _)))
                     * {
                     *  MessageBox.Show("Failed to add JPG icon");
                     *  modpak.ClosePak();
                     *  return;
                     * }
                     */
                    Image img = Image.FromStream(iconStream);
                    customIconImage = new Bitmap(img.GetThumbnailImage(128, 128, null, new IntPtr()));
                }
                else
                if (useOldPNGImage)
                {
                    var oldpngStream = mainPak.ExportFileAsStream(ModPNGImageFileName);

                    /*
                     * if ((Path.GetExtension(NewCustomImage).ToLower() == ".png") && (!modpak.AddFileFromStream(ModPNGImageFileName, oldpngStream, DateTime.Now, DateTime.Now, false, out _)))
                     * {
                     *  MessageBox.Show("Failed to copy PNG icon");
                     *  modpak.ClosePak();
                     *  return;
                     * }
                     */
                    Image img = Image.FromStream(oldpngStream);
                    customIconImage = new Bitmap(img.GetThumbnailImage(128, 128, null, new IntPtr()));
                }
                else
                if (useOldJPGImage)
                {
                    var oldjpgStream = mainPak.ExportFileAsStream(ModJPGImageFileName);

                    /*
                     * if ((Path.GetExtension(NewCustomImage).ToLower() == ".png") && (!modpak.AddFileFromStream(ModJPGImageFileName, oldjpgStream, DateTime.Now, DateTime.Now, false, out _)))
                     * {
                     *  MessageBox.Show("Failed to copy PNG icon");
                     *  modpak.ClosePak();
                     *  return;
                     * }
                     */
                    Image img = Image.FromStream(oldjpgStream);
                    customIconImage = new Bitmap(img.GetThumbnailImage(128, 128, null, new IntPtr()));
                }
                else
                {
                    // No image used
                }

                if ((cbCreateSFX.Checked) && (customIconImage != null))
                {
                    // Create some temp files
                    string tempIconFile = Path.GetTempFileName(); // .GetTempPath() + "aamod_tmp.ico";
                    string tempEXEFile  = Path.GetTempFileName(); // .GetTempPath() + "aamod_tmp.exe";
                    try
                    {
                        // Very hacky way of adding/editing a icon to the sfx exe to add

                        // Create 64x64 "thumbnail" as icon
                        var pu   = GraphicsUnit.Pixel;
                        var cImg = customIconImage.Clone(customIconImage.GetBounds(ref pu), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                        cImg.SetResolution(72, 72);
                        var tempImg = cImg.GetThumbnailImage(64, 64, null, new IntPtr());
                        // tempImg.Save(Path.GetTempPath() + "tmp_aamod.bmp");

                        // Create and Save temporary ico file
                        // Icon ic = ImageToIcon(tempImg);
                        var tempBitmap = new Bitmap(tempImg, new Size(64, 64));

                        MemoryStream iconStream = SaveAsIconMemoryStream(tempBitmap);
                        // MemoryStream iconStream = new MemoryStream();
                        // ic.Save(iconStream);
                        FileStream iconStreamFile = File.Create(tempIconFile);
                        iconStream.Position = 0;
                        iconStream.CopyTo(iconStreamFile);
                        iconStreamFile.Close();

                        // Save temporary exe file
                        MemoryStream exeStream = new MemoryStream(Properties.Resources.AAModSFX);
                        FileStream   fs        = File.Create(tempEXEFile);
                        exeStream.CopyTo(fs);
                        fs.Close();
                        exeStream.Close();


                        // Create IconFile from temporary ico file
                        IconFile icf = new IconFile(tempIconFile);

                        // Delete old Icon resources
                        ResourceInfo vi = new ResourceInfo();
                        vi.Load(tempEXEFile);
                        foreach (ResourceId id in vi.ResourceTypes)
                        {
                            if (id.ResourceType != Kernel32.ResourceTypes.RT_GROUP_ICON)
                            {
                                continue;
                            }
                            foreach (Resource resource in vi.Resources[id])
                            {
                                resource.DeleteFrom(tempEXEFile);
                            }
                        }

                        // Add to IconDirectory
                        IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(icf);
                        IconResource          icr = new IconResource();
                        // Save to temporary exe
                        iconDirectoryResource.SaveTo(tempEXEFile);

                        // Read temporary exe back into stream
                        fs        = File.OpenRead(tempEXEFile);
                        exeStream = new MemoryStream();
                        fs.CopyTo(exeStream);

                        // Add modified exe to modpak
                        if (!modpak.AddFileFromStream(SFXInfoFileName, exeStream, DateTime.Now, DateTime.Now, true, out _))
                        {
                            MessageBox.Show("Failed to add modified SFX executable");
                            modpak.ClosePak();
                            return;
                        }
                    }
                    catch (Exception x)
                    {
                        MessageBox.Show("Exception editing icon:\n" + x.Message);
                        modpak.ClosePak();
                        return;
                    }
                    try
                    {
                        File.Delete(tempEXEFile);
                    }
                    catch { }
                    try
                    {
                        File.Delete(tempIconFile);
                    }
                    catch { }
                }
                else
                // If you want to use the aamod as a SFX, the .exe needs to be the first file in the pak
                if (cbCreateSFX.Checked)
                {
                    // This AAModSFX resource is loaded from the RELEASE build of the AAMod project, make sure it's compiled as release first if you made changes to it
                    MemoryStream sfxStream = new MemoryStream(Properties.Resources.AAModSFX);
                    // We will be possibly be editing the icon, so it's a good idea to have some spare space here
                    if (!modpak.AddFileFromStream(SFXInfoFileName, sfxStream, DateTime.Now, DateTime.Now, true, out _))
                    {
                        MessageBox.Show("Failed to add SFX executable");
                        modpak.ClosePak();
                        return;
                    }
                }

                var modInfoStream = AAPak.StringToStream(tDescription.Text);
                if (!modpak.AddFileFromStream(ModInfoFileName, modInfoStream, DateTime.Now, DateTime.Now, false, out _))
                {
                    MessageBox.Show("Failed to add description");
                    modpak.ClosePak();
                    return;
                }

                if (customIconImage != null)
                {
                    MemoryStream imgStream = new MemoryStream();
                    customIconImage.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png);
                    if (!modpak.AddFileFromStream(ModPNGImageFileName, imgStream, DateTime.Now, DateTime.Now, false, out _))
                    {
                        MessageBox.Show("Failed to add icon image");
                        modpak.ClosePak();
                        return;
                    }
                }


                // Copy all files
                foreach (var fi in mainPak.files)
                {
                    if (fi.name.StartsWith(ModFileFolderName))
                    {
                        continue;
                    }
                    var ms = mainPak.ExportFileAsStream(fi);
                    if (!modpak.AddFileFromStream(fi.name, ms, DateTime.FromFileTimeUtc(fi.createTime), DateTime.FromFileTimeUtc(fi.modifyTime), false, out _))
                    {
                        MessageBox.Show("Failed to copy \n" + fi.name + "\nAborting !", "Copy Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        modpak.ClosePak();
                        return;
                    }
                }
                modpak.ClosePak();

                MessageBox.Show("AAMod create completed !", "AAMod Create", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
            }
            catch (Exception x)
            {
                MessageBox.Show("Exception: " + x.Message);
            }
        }
	public GroupIconResource(IconResource[] InIcons)
	{
		Icons = InIcons;
	}
Exemple #23
0
 private void Instance_IconChanged(IconResource icon)
 {
     Dispatcher.InvokeAsync(() => Icon.Content = IconResourceLoader.Load(icon));
 }
 public static void Dump(IconResource rc)
 {
     Console.WriteLine(" Icon {0}: {1} ({2} byte(s))",
                       rc.Header.nID, rc.ToString(), rc.ImageSize);
 }
 private void Window_IconChanged(IconResource icon)
 {
     Dispatcher.InvokeAsync(() => Icon.Content = IconResourceLoader.Load(window.Icon));
 }
Exemple #26
0
        public PeReader(string fPath)
        {
            try
            {
                m_fPath   = fPath;
                m_peImage = new PEImage(File.ReadAllBytes(fPath));

                if (m_peImage.ImageNTHeaders.OptionalHeader.DataDirectories.Length >= 14)
                {
                    ImageDataDirectory DotNetDir = m_peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];
                    if (m_peImage.ToFileOffset(DotNetDir.VirtualAddress) != 0 && DotNetDir.Size >= 72)
                    {
                        m_cor20Header = new ImageCor20Header(m_peImage.CreateStream(m_peImage.ToFileOffset(DotNetDir.VirtualAddress), 0x48), false);
                        if (m_peImage.ToFileOffset(m_cor20Header.MetaData.VirtualAddress) != 0 && m_cor20Header.MetaData.Size >= 16)
                        {
                            m_isManaged = true;
                            uint           mdSize   = m_cor20Header.MetaData.Size;
                            RVA            mdRva    = m_cor20Header.MetaData.VirtualAddress;
                            MetaDataHeader mdHeader = new MetaDataHeader(m_peImage.CreateStream(m_peImage.ToFileOffset(mdRva), mdSize), false);
                            m_RunTimeVersion = mdHeader.VersionString;
                        }
                    }
                }

                if (m_isManaged == true)
                {
                    ImageSectionHeader sect = m_peImage.ImageSectionHeaders.Where(f => f.DisplayName == ".rsrc").FirstOrDefault();
                    if ((sect != null))
                    {
                        ImageDataDirectory resourceTable = m_peImage.ImageNTHeaders.OptionalHeader.DataDirectories[2];
                        if ((resourceTable != null))
                        {
                            uint rva  = (uint)resourceTable.VirtualAddress;
                            uint size = sect.VirtualSize > 0 ? sect.VirtualSize : sect.SizeOfRawData;

                            if (rva >= (uint)sect.VirtualAddress && rva < (uint)sect.VirtualAddress + size)
                            {
                                Stream            StreamRead  = m_peImage.CreateFullStream().CreateStream();
                                long              baseAddress = StreamRead.Seek(sect.PointerToRawData + (rva - (uint)sect.VirtualAddress), SeekOrigin.Begin);
                                ResourceDirectory dirInfo     = new ResourceDirectory(StreamRead, baseAddress);

                                if ((dirInfo != null))
                                {
                                    using (BinaryReader reader = new BinaryReader(StreamRead))
                                    {
                                        dirInfo.Read(reader, true, 0);

                                        ResourceEntry        IconGroup  = null;
                                        List <ResourceEntry> IconImages = new List <ResourceEntry>();

                                        foreach (ResourceDirectory dir in dirInfo.Directorys)
                                        {
                                            if (dir.DirectoryEntry.Name == Convert.ToUInt32(Win32ResourceType.RT_GROUP_ICON))
                                            {
                                                IconGroup = dir.GetFirstEntry();
                                                break;
                                            }
                                        }

                                        foreach (ResourceDirectory dir in dirInfo.Directorys)
                                        {
                                            if (dir.DirectoryEntry.Name == Convert.ToUInt32(Win32ResourceType.RT_ICON))
                                            {
                                                IconImages = dir.GetAllEntrys();
                                                IconImages.Reverse();
                                                break;
                                            }
                                        }

                                        if (IconGroup != null)
                                        {
                                            IconResource icon = new IconResource(StreamRead, IconGroup.DataAddress, sect.PointerToRawData, (uint)sect.VirtualAddress);
                                            icon.Seek();
                                            if (!icon.Read(reader, IconImages))
                                            {
                                                m_MainIcon = null;
                                            }
                                            m_MainIcon = icon.GetIcon(reader);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Interaction.MsgBox(ex);
            }
        }
 internal ExternalApplicationWindow(IconResource icon, INativeMethods nativeMethods, IntPtr handle)
 {
     this.Handle        = handle;
     this.Icon          = icon;
     this.nativeMethods = nativeMethods;
 }
	public void WriteIconHeader(BinaryWriter Writer, IconResource Icon)
	{
		Writer.Write(Icon.Width);
		Writer.Write(Icon.Height);
		Writer.Write(Icon.ColorCount);
		Writer.Write((byte)0);
		Writer.Write(Icon.Planes);
		Writer.Write(Icon.BitCount);
		Writer.Write(Icon.Data.Length);
	}