2011-08-30 4 views
1

Мне нужно создать как 10k различных значков для тестирования, может быть в C# или powershell. У меня на самом деле 10k идентичных файлов значков с разными именами, и я думал, что могу легко прочитать двоичный значок, конвертировать в байты, ввести случайное число и записать обратно в файл, но это не работает так, как я вижу.Как изменить действительный значок окна программно?

$fi = @(Get-ChildItem D:\icons -rec | ForEach-Object -Process {$_.FullName}) # | select -first $amount) 
$no = 0 

foreach($i in $fi) 
{ 
    $array = Read-FileByte $i; 
    $array = $array + [System.Text.Encoding]::UTF8.GetBytes($no) 
    [System.IO.File]::WriteAllBytes($i, $array) 
    $no++ 
} 

После этого значки запуска кода по-прежнему считаются идентичными окнами.

ALternative way будет создавать действительные значки 10k программно, есть ли способ сделать это? благодаря

ответ

2
//fixed 
[DllImport("user32.dll", SetLastError = true)] static extern bool DestroyIcon(IntPtr hIcon); 
     public Icon MakeRandomIcon() 
     { 
      using (Bitmap bmp = new Bitmap(size, size)) 
      using (Graphics g = Graphics.FromImage(bmp)) 
      { 
       for (int it = 0; it < 20; it++) this.GetRandomPainter()(g); 
       g.Dispose(); 
       IntPtr hIcon = bmp.GetHicon(); 
       Icon temp = Icon.FromHandle(hIcon); 
       Icon ico = (Icon)temp.Clone(); 
       temp.Dispose(); 
       DestroyIcon(hIcon); 
       return ico; 
      } 
     } 


//thanks Miguel again. 
+0

Спасибо, что отправили исправление !!! знак равно –

4

Вы можете использовать этот код, чтобы создать столько случайных иконок, как вам нравится:

using System; 
using System.Linq; 
using System.Drawing; 
using System.IO; 
static class Program 
{ 
    [STAThread] 
    static void Main() 
    { 
     var gen = new RandomIconGenerator(32); 
     var dir = new DirectoryInfo(@"C:\RandIcons\"); 
     if (!dir.Exists) dir.Create(); 
     for (int it = 0; it < 1000; it++) 
      using (var s = new FileStream(@"C:\RandIcons\" + "icon-" + it + ".ico", FileMode.Create)) 
       gen.MakeRandomIcon().Save(s); 
    } 
} 
/// <summary> 
/// Generates random icons using various colored shapes and lines, using available brushes and pens. 
/// </summary> 
public class RandomIconGenerator 
{ 
    Random r = new Random(); 
    Pen[] pens = typeof(Pens).GetProperties().Select(p => (Pen)p.GetValue(null, null)).ToArray(); 
    Brush[] brushes = typeof(Brushes).GetProperties().Select(p => (Brush)p.GetValue(null, null)).ToArray(); 
    int size; 
    public RandomIconGenerator(int size) { this.size = size; } 
    public Icon MakeRandomIcon() 
    { 
     using (Bitmap bmp = new Bitmap(size, size)) 
     using (Graphics g = Graphics.FromImage(bmp)) 
     { 
      for (int it = 0; it < 20; it++) this.GetRandomPainter()(g); 
      g.Flush(); 
      return Icon.FromHandle(bmp.GetHicon()); 
     } 
    } 
    private Pen GetRandomPen() { return this.pens[this.r.Next(this.pens.Length)]; } 
    private Brush GetRandomBrush() { return this.brushes[this.r.Next(this.brushes.Length)]; } 
    private Action<Graphics> GetRandomPainter() 
    { 
     switch (r.Next(5)) 
     { 
      case 0: return g => g.DrawLine(this.GetRandomPen(), this.GetRandomPoint(), this.GetRandomPoint()); 
      case 1: return g => g.DrawRectangle(this.GetRandomPen(), this.GetRandomRect()); 
      case 2: return g => g.DrawEllipse(this.GetRandomPen(), this.GetRandomRect()); 
      case 3: return g => g.FillRectangle(this.GetRandomBrush(), this.GetRandomRect()); 
      case 4: return g => g.FillEllipse(this.GetRandomBrush(), this.GetRandomRect()); 
      default: throw new Exception(); 
     } 
    } 
    private Rectangle GetRandomRect() 
    { 
     var p0 = this.GetRandomPoint(); 
     return new Rectangle(p0, new Size(this.GetRandomPoint()) - new Size(p0)); 
    } 
    private int GetRandomPos() { return this.r.Next(this.size); } 
    private Point GetRandomPoint() { return new Point(this.GetRandomPos(), this.GetRandomPos()); } 
} 
+0

Привет Мигель, спасибо человеку, отлично работает, хотя после того, как именно 3326 иконками я получаю исключение , но я думаю, что могу понять: Unhandled Exception: System.Runtime.InteropServices.ExternalException: Общая ошибка произошла в GDI +. на System.Drawing.Bitmap.GetHicon() в RandomIconGenerator.MakeRandomIcon() в Program.Main (String [] арг) –

+0

использования (график г = Graphics.FromImage (ВМР)) { для (INT = это 0; it <20; это ++) this.GetRandomPainter() (g); g.Flush(); return Icon.FromHandle (bmp.GetHicon()); <---- почему дует здесь } –

+0

Привет! У меня была такая же проблема здесь ... это кажется случайным. Я посмотрю на это позже и попытаюсь выяснить причину. –

Смежные вопросы