יום חמישי, 11 באפריל 2024

merge multiple docx

 בשביל לחבר קבצי docx צריך להוסיף reference לקבצים הבאים:

חלון Solution Explorer > לחיצה ימנית על References > לחיצה על Add References

להוריד NuGet או מהאינטרנט את הקבצים ולהוסיף:

Telerik.Windows.Documents.Flow.dll

קוד C#:

void MergeDocx(List<string> files, string result_file)
{
   RadFlowDocument target = new RadFlowDocument();
   RadFlowDocument source = new RadFlowDocument();
   DocxFormatProvider provider = new DocxFormatProvider();
   for (int i = 0; i < file.Count; i++)
  {
     using(Stream input = File.OpenRead(files[i]))
     {
          target.Merge(provider.Import(input));
      }
   }
   byte[] ba = provider.Export(target);
   File.WriteAllBytes(result_file, ba);
 }

convert docx to pdf telerik

 בשביל להמיר docx ל-pdf צריך להוסיף reference לקבצים הבאים:

חלון Solution Explorer > לחיצה ימנית על References > לחיצה על Add References

להוריד NuGet או מהאינטרנט את הקבצים ולהוסיף:

Telerik.Windows.Documents.Core.dll
Telerik.Windows.Documents.Flow.dll
Telerik.Windows.Documents.Flow.FormatProviders.Pdf.dll

קוד C#:

void ConvertDocxToPdf(string docxpath, string pdfpath)
{
  var docxProvider = new DocxFormatProvider();
  var pdfProvider = new PdfFormatProvider();
  byte[] docxByteArr = File.ReadAllBytes(docxpath);
  var doc = docxProvider.Import(docxByteArr);
  byte[] resultPdfByteArr = pdfProvider.Export(doc);
  File.WriteAllBytes(pdfpath, resultPdfByteArr);
}

יום שני, 12 ביוני 2023

Search in list

חיפוש מחרוזת תווים בתוך מאגר מילים: - מיושם בתוכנת C# Winform:
List<string> listTemp = new List<string>();
private void textBox1_TextChanged(object sender, EventArgs e)
{
  var tmp = new List<string>();
  
  //restore source list
  if (textBox1.Text.Length == 0 || textBox1.Text.Length > 1)
    richTextBox1.Text = String.Join(" ", listTemp);
  
  if (textBox1.Text.Length > 0)
  {
    //copy from src to out-temp (happens only once)
    if (textBox1.text.Length == 1 && listTemp.Count == 0)
      listTemp = richTextBox1.Text.Split(' ').ToList();
  
    //filter
    foreach (string item in richTextBox1.Text.Split(' ').ToList())
    {
      if (item.Contains((textBox1.text))
        tmp.Add(item);
    }
    richTextBox1.Text = String.Join(" ", tmp);
  }
}

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
  if (richTextBox1.Focused)
    listTemp.Clear();
}

יום שני, 28 בנובמבר 2022

WPF - בחירת עמודות מטופס חיצוני - Column Chooser

בשביל שימוש בפקדים של telerik צריך להוסיף ref לקבצים:

Telerik.Windows.Controls
Telerik.Windows.Controls.GridView
Telerik.Windows.Controls.Input
Telerik.Windows.Data

  https://www.telerik.com/blogs/how-to-column-chooser-for-radgridview-for-silverlight-and-wpf

MainWindow.xaml

MainWindowxaml.cs

dummy class

VisisbilityToBoolConverter

ColumnChooser xaml page

ColumnChooser xaml.cs page

יום שני, 16 במאי 2022

הורדה ישירה מחנות מיקרוסופט

1. צריך למצוא את האפליקציה שרוצים להוריד, ולהעתיק את id שלה. 
למשל עבור WinDbg Preview   הכתובת היא:
https://apps.microsoft.com/store/detail/windbg-preview/9PGJGD53TN86
הקוד הוא 9PGJGD53TN86

2. ללכת לאתר: https://store.rg-adguard.net   לבחור ברשימה הנפתחת את product id להזין שם הקוד שהעתקנו,וללחוץ v. 
כמה שניות והכתובות יופיעו. 

 3. צריך להוריד קובץ appx

4. ע"פ אתר https://github.com/MicrosoftFeedback/WinDbg-Feedback/issues/19       צריך לעשות לקובץ unzip לתוך תיקיה ולהריץ את קובץ DbgX.Shell.exe 

5. ע"פ אתר https://digitalitskills.com   צריך להריץ PowerShell ולהתקין:
PS C:\WINDOWS\System32\Add-AppxPackage -Path C:\windbg.appx

יום ראשון, 30 בינואר 2022

מיפוי כונן רשת לאות כונן במחשב

מיפוי כונן רשת - נעשה בעבר כדי למפות database מרוחק

* חשוב לוודא תקשורת בין שני המחשבים (בעזרת ping)

שלבים:

1. למצוא את כתובת ip של המחשב (עם database) - למשל 125.16.54.77

2. לעשות מיפוי כונן רשת - לחיצה ימנית על סמל 'המחשב שלי' >  בחירת אות כונן (למשל A:) > 

לבחור ספריה בכונן הרשת שאנו רוצים, למשל:

\\125.16.54.77\d$\databases\

צריך לבחור ב-Connect using different Credntials אם רוצים להזין שםמשתמש וסיסמה לכונן.

3. לחיצה על Finish - אם סימנו V בסעיף הקודם, אז יפתח חלון Windows Security - נלחץ על More Choices - Use Different Accout ונזין את פרטי ההתחברות

4. כדי לנתקן מיפוי כונן - יש ללחוץ לחיצה ימנית על הכונן בחלון 'המחשב שלי' > Disconnect network drive





יום שלישי, 11 בינואר 2022

C# - Udp Server & Client

UDP Server:


  Thread trdServerUdp = 
     new Thread(new ThreadStart(serverThread));
  trdServerUdp.Start();
}

void ServerThread() {
  UdpClient server = new UdpClient(port);
  while (true) {
    IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(ip), port);
    byte[] receiveBytes = server.Receive(ref remoteIpep);
    string str = Encoding.ASCII.GetString(receiveBytes);
    Console.WriteLine($"{remoteIpep}: {str}");
  }
}
  
UDP Client:


  string ip = "127.0.0.1";
  int port = 8080;

  string input;
  UdpClient client = new UdpClient();
  client.Connect(ip, port);

  byte[] data;
  while (true) {
    input = Console.ReadLine();
    if (input == "exit") break;
    data = Encoding.ASCII.GetBytes(input);
    client.Send(data, data.Length);
  }
}
  

C# - Tcp Server & Client

קוד סרבר שמחכה עד שקליינט יתחבר, ואז מקבל הודעות ומחזיר אותן אל הקליינט:

TCP Server:

void server_foo(){
  int port = 9050;
  int recv;
  byte[]data = new byte[1024];
  IPEndPoint ipep = new IPEndPoint(IPAdress.Any, port);
  Socket newsock = new Socket(AddressFamily.InterNetwork, 
                        SocketType.Stream,
                        ProtocolType.Tcp);

  newsock.Bind(ipep);
  newsock.Listen(10);

  Console.WriteLine("waiting for client...");
  Socket client = newsoc.Accept();

  IPEndPoint clientep = (IPEndPoint )client.RemoteEndPoint;
  Console.WriteLine($"Connected with {clientep.Address} at port {clientep.Port}");
  data = Encoding.ASCII.GetBytes("[CONNECTED TO SERVER]");
  client.Send(data, data.Length, SocketFlag.None);

  while (true) {
     try {
        data = new byte[1024];
        recv = client.Receive(data);
        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
        if(recv == 0) break; // 0 == exit
        client.Send(data, recv, SocketFlags.None);
     }
     catch (Exception ex) {
        Console.WriteLine(ex.Message);
        Console.ReadLine();
        break;
     }
     finally {
        client.Close();
        newsock.Close();
     }
  }
  Console.WriteLine($"Disconnected from {clientep.Address}:{clientep.Port}");
}
  
לחץ כאן כדי להעתיק את הקוד

קוד קליינט שמנסה כל 5 שניות להתחבר:

TCP Client:

void client_foo(){
   byte[]data = new byte[1024];
   string input, stringData;
   IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port);
   Socket server = new Socket(AddressFamily.InterNetwork, 
        SocketType.Stream,
        ProtocolType.Tcp);
  
  //try to connect:
  while (true) {
    try {
      server.Connect(ipep);
      Console.WriteLine("CONNECTED");
      break;
    }
    catch {
      //try to reconnect:
      Console.WriteLine("Unable to connect: " + ex.Message);
      Console.WriteLine("Trying to reconnect in:");
  
      for (int i = 1; i <= 5; i++) {
        Console.Write(i);
        Console.CursorLeft = 0;
        Thread.Sleep(1000);
      }
    }
  }

  // connected
  int recv = server.Receive(data);
  stringData = Encoding.ASCII.GetString(data, 0 ,recv);
  Console.WriteLine(stringData);
                            
  while (true) {
    input = Console.ReadLine();
    if (input == "exit") break;

    // send message
    server.Send(Encoding.ASCII.GetBytes(input));
                            
    // get message back
    data = new byte[1024];
    recv = server.Receive(data);
    stringData = Encoding.ASCII.GetString(data, 0 ,recv);
    Console.WriteLine(stringData);
  }

  //close connection to server
  Console.WriteLine("Disconnected from server");
  server.Shutdown(SocketShutdown.Both);
  server.Close();
}
לחץ כאן כדי להעתיק את הקוד

יום רביעי, 10 בנובמבר 2021

hack family safety lock

איך לפרוץ את נעילת הגנת הורים של windows

כאשר החשבון נעול מפני מנגנון הגנת משפחה (Family Safety Monitor by Microsoft Corporation), ומאפשר למשל כניסה הבאה רק ב-8 בבוקר, ניתן לפרוץ אותו בדרך הבאה:

להדליק ולכבות את המחשב לפני שהוא נכנס ל-windwos מספר פעמים עד שהמחשב יעלה במצב לתיקון בעיות אתחול.

ניתן לראות הדגמה לכניסה למערכת הקבצים כאן:

https://www.youtube.com/watch?v=n7KEwXbFlIU

צריך להיכנס למערכת הקבצים ולשנות את שם הקובץ 

c:\windows\system32\wpcmon.exe

לשם אחר - למשל להוסיף לשם הקובץ 1111

ואז להפעיל את המחשב מחדש.

הקובץ הזה הוא זה שמפעיל את מנגנון הגנת הורים, וכעת הוא לא יפעל בעליית windows

יום חמישי, 15 ביולי 2021

חלוקת מסך בדפדפן האינטרנט

ניתן לבצע חלוקת מסך אופקית או אנכית בדפדפן האינטרנט לשני אתרים בו זמנית!
לשם כך, לחצו ctrl+d בשביל יצירת סימניה חדשה ריקה, ובחרו ליצור אותה בסרגל הסימניות.

לאחר מכן, לחצו לחיצה ימנית על הסימניה ובחרו עריכה.
יופיעו שני שדות לעריכה: 
שם - כתבו חלוקה אנכית (או אופקית)
כתובת - לחצו לחיצה משולשת לבחירת כל הקוד, ואז העתיקו והדביקו אותו:

חלוקת מסך אנכית

חלוקת מסך אופקית

יום ראשון, 15 בנובמבר 2020

איך להריץ קובץ bat בתור מנהל מערכת

יש להוסיף את הקוד הזה בתחילת הקובץ, ובסופו את הקוד שנרצה להריץ בתור מנהלי מערכת:

כיצד ליצור קובץ bat:

1. יש לפתוח את התיקיה בה נרצה שיהיה הקובץ

2. לחיצה ימנית על שטח ריק > ניצור קובץ txt

3. נכתוב בתוכו את תוכן הקובץ ונשמור

4. נשנה את סיומת הקובץ מ-txt ל-bat - למשל

snir.txt  >   snir.bat

יום רביעי, 18 במרץ 2020

החבאת זיפ בתוך תמונה

אפשר 'להתחכם' ולהחביא קובץ ZIP שנרצה לשמור סודי,
ולשנות את סיומת הקובץ לכל סיומת שנבחר, למשל jpg .
אבל ברגע שננסה לפתוח את ה'תמונה' החדשה שעכשיו יצרנו ניתקל בהודעת שגיאה.


בשביל ליצור קובץ תמונה תקני שיתפקד כקובץ zip בשינוי סיומת הקובץ, יש לנקוט צעדים הבאים:
1. מקם את שני הקבצים , למשל - snir.jpg , elgabsi.zip - באותה תיקיה.
2. הקלד את הפקודה:
copy /b snir.jpg + elgabsi.zip ha_gever.jpg 
    כאשר ha_gever.jpg יהיה הקובץ הסופי שיכיל את שני הקבצים - המכווץ והתמונה - יחד .
    b/ משמעו קיצור ל "בינארי". הפקודה 'תעתיק' יחד את שני הקבצים.
    סדר רישום הקבצים בפקודה חשוב.
3. כעת נוצר הקובץ הסופי - ha_gever.jpg (אפשרי גם ליצור קובץ סופי בכל פורמט).
    שנה את סיומת הקובץ ע"מ להשתמש בו במתכונתו האחרת.

יום שבת, 26 באוקטובר 2019

איך לקבל את קוד product key של ווינדוס

  • פתח את 'פנקס הרשימות' - notepad
  • העתק את הקוד
  • הדבק את הקטע הבא בקובץ product-key.vbs


Option Explicit 

Dim objshell,path,DigitalID, Result 
Set objshell = CreateObject("WScript.Shell")
'Set registry key path
Path = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\"
'Registry key value
DigitalID = objshell.RegRead(Path & "DigitalProductId")
Dim ProductName,ProductID,ProductKey,ProductData
'Get ProductName, ProductID, ProductKey
ProductName = "Product Name: " & objshell.RegRead(Path & "ProductName")
ProductID = "Product ID: " & objshell.RegRead(Path & "ProductID")
ProductKey = "Installed Key: " & ConvertToKey(DigitalID) 
ProductData = ProductName  & vbNewLine & ProductID  & vbNewLine & ProductKey
'Show messbox if save to a file 
If vbYes = MsgBox(ProductData  & vblf & vblf & "Save to a file?", vbYesNo + vbQuestion, "BackUp Windows Key Information") then
   Save ProductData 
End If



'Convert binary to chars
Function ConvertToKey(Key)
    Const KeyOffset = 52
    Dim isWin8, Maps, i, j, Current, KeyOutput, Last, keypart1, insert
    'Check if OS is Windows 8
    isWin8 = (Key(66) \ 6) And 1
    Key(66) = (Key(66) And &HF7) Or ((isWin8 And 2) * 4)
    i = 24
    Maps = "BCDFGHJKMPQRTVWXY2346789"
    Do
        Current= 0
        j = 14
        Do
           Current = Current* 256
           Current = Key(j + KeyOffset) + Current
           Key(j + KeyOffset) = (Current \ 24)
           Current=Current Mod 24
            j = j -1
        Loop While j >= 0
        i = i -1
        KeyOutput = Mid(Maps,Current+ 1, 1) & KeyOutput
        Last = Current
    Loop While i >= 0 
    keypart1 = Mid(KeyOutput, 2, Last)
    insert = "N"
    KeyOutput = Replace(KeyOutput, keypart1, keypart1 & insert, 2, 1, 0)
    If Last = 0 Then KeyOutput = insert & KeyOutput
    ConvertToKey = Mid(KeyOutput, 1, 5) & "-" & Mid(KeyOutput, 6, 5) & "-" & Mid(KeyOutput, 11, 5) & "-" & Mid(KeyOutput, 16, 5) & "-" & Mid(KeyOutput, 21, 5)
   
    
End Function
'Save data to a file
Function Save(Data)
    Dim fso, fName, txt,objshell,UserName
    Set objshell = CreateObject("wscript.shell")
    'Get current user name 
    UserName = objshell.ExpandEnvironmentStrings("%UserName%") 
    'Create a text file on desktop 
    fName = "C:\Users\" & UserName & "\Desktop\WindowsKeyInfo.txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set txt = fso.CreateTextFile(fName)
    txt.Writeline Data
    txt.Close
End Function


המקור מגיע מכאן:
https://www.slothparadise.com/how-to-get-windows-product-key

https://www.youtube.com/watch?v=wzuCgm7dIEc

יום שלישי, 10 בספטמבר 2019

VS_FileCompare

השוואת קבצים ע"י Visual Studio
ללא תוכנה חיצונית

כתבו את הקוד הבא בקובץ cmd
VS_FileCompare.cmd



השוואת הקבצים תיעשה ע"י כתיבת שורת הקוד הבאה


כאשר Form1.cs, Form2.cs הם שמות הקבצים שרוצים להשוות

יום חמישי, 22 בנובמבר 2018

כתיבה וטעינה של קבצי XML - שפת c#

כתיבה וטעינה של קבצי XML בשפת c#
ניתן לכתוב/לקרוא XML לכל סוג של מחלקה/אובייקט, גם אם יהיה זה אובייקט בסיסי (לדוגמה string) או מחלקה שנוצרה על-ידי המשתמש:

public class SnirXmlHandler
{
   /// <summary>save xml</summary>
   public static void Save<T>(T t, string filename)
   {
      try 
      {
         XmlSerializer serializer = new XmlSerializer(typeof(T));
         using (TextWriter textWriter = new StreamWriter(filename)) 
         {
            serializer.Serialize(textWriter, t);
            textWriter.Close();
         }
      }
      catch (Exception ex) { throw; }
   }

   /// <summary>load xml file</summary>
   public static T Load<T>(string filename)
   {
      T t;
      try 
      {
         XmlSerializer deserializer = new XmlSerializer(typeof(T));
         using (TextReader textReader = new StreamReader(filename)) 
         {
            t = (T)deserializer.Deserialize(textReader);
            textReader.Close();
         }
      }
      catch (Exception ex) { throw; }
      return t;
   }
}

שימוש לדוגמה:
public class MyClass
{
    public string Name { get; set; }
    public int[] Age { get; set; }
    public MyClass2 Mc2 { get; set; }
}

public class MyClass2
{
    public int[] Num { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass myclass = new MyClass()
        {
            Name = "snir",
            Age = new int[] { 1, 2, },
            Mc2 = new MyClass2 
            {
                Num = new int[] { 10, 45 }
            }
        };
        SnirXmlHandler.Save(myclass, "snir.xml");
        MyClass mc = SnirXmlHandler.Load("snir.xml");
    }
}



קובץ XML תוצאה:
<myclass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <age> <name>snir</name> <age> <int>1</int> <int>2</int> </age> <mc2> <num> <int>10</int> <int>45</int> </num> </mc2> </myclass>

קונטרול webbrowser לגרסת Internet Explorer הכי גבוהה

כיצד להשתמש בקונטרול C# webbrowser שישתמש בגרסת internet explorer גבוהה (ולא גרסה 7 - ברירת מחדל)

1. יש לגשת לתיקיה זו ברגיסטרי
ולשנות/להוסיף מפתח זה עבור כל תוכנה רצויה
>HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION

לערכים הבאים עבור גרסאות ie (בהתאמה לי המספר)
  • 7000 , 8888, 9000, 10000, 11000 (standards-based !DOCTYPE directives)
  • 8888, 9999, 10001, 11001 (regardless of the !DOCTYPE directive)

2. לאחר מכן, צריך להגדיר את internet explorer 11, לפי התמונות להלן:
(אפשרות זו אינה קיימת ב-internet explorer edge)
תרגום לעברית: הגדרות של תצוגת תאימות


יש אפשרות לעשות שהתוכנה תרשום את עצמה ברגיסטרי עבור שימוש בגרסה IE גבוהה יותר:
/// <summary>
/// Set IE Version to registry.
/// Options: 8888, 9999, 10001, 11001 (regardless of the !DOCTYPE directive) 
/// 7000, 8000, 9000, 10000, 11000 (standards-based !DOCTYPE directives)
/// </summary>
private void SetIeVersionInRegistery(string version)
{
   try
   {
      string key_str = @"Software\Microsoft\Internet Explorer\
                                      Main\FeatureControl
                                      \FEATURE_BROWSER_EMULATION";
      string exe_name = System.AppDomain.CurrentDomain.FriendlyName;

      RegistryKey myKey = Registry.CurrentUser.OpenSubKey(key_str, true);

      using (RegistryKey key = myKey.OpenSubKey(key_str, true))
      {
         if (myKey != null)
         {
            myKey.SetValue(exe_name, version, RegistryValueKind.DWord);
         }
      }
   }
   catch (Exception ex)
   {
      throw ex;
   }
}

יום שני, 8 באוקטובר 2018

איך לדחוף dll לתוך קובץ exe


1. במאפיינים של קובץ ה-dll שנוסף בתור reference, יש לשנות את Copy Local=False
2. את אותו קובץ שהוספנו בתור reference יש לגרור אל תוך הפרויקט ב-solution explorer
3. יש לשנות את המאפיין של קובץ זה: Build Action=Embedded
4. יש להעתיק את הקוד הבא למקום שלפני Application.Run בתוך הקוד של exe:

static class Program
{
   /// <summary>
   /// The main entry point for the application.
   /// </summary>
   [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            Application.Run(new Form1());
        }

   private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
   {
            string dllName = args.Name.Contains(',') 
                ? args.Name.Substring(0, args.Name.IndexOf(',')) 
                : args.Name.Replace(".dll", "");
            dllName = dllName.Replace(".", "_");
            if (dllName.EndsWith("_resources"))
                return null;

            using (var stream = Assembly.GetExecutingAssembly()
                .GetManifestResourceStream(GetCurrentNamespace() + "." + dllName + ".dll"))
            {
                byte[] assemblyData = new byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return Assembly.Load(assemblyData);
            }
   }

   [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.NoInlining)]
   public static string GetCurrentNamespace()
   {
            return 
    System.Reflection.Assembly.GetCallingAssembly().EntryPoint.DeclaringType.Namespace;
    }
 }

יום שישי, 20 באפריל 2018

שפת בסיס נתונים

יצרתי אתר אינטרנט וניסיתי להזין נתונים בעברית - אבל הכל נקלט כג'יבריש.
לאחר מעט שוטטיות באינטרנט התברר לי שהקולז'ן של בסיס הנתונים שלי הוא:
SQL_Latin1_General_CP1_CI_AS

כלומר לטינית.
כדי לשנות אותו עשיתי:

USE master;  
ALTER DATABASE elgabsiDb
COLLATE Hebrew_CI_AS;  


כדי לבדוק מה הקולזן של בסיס הנתונים:
Select name,collation_name From sys.databases
התוצאה:



להלן מעט אתרים עם הפרטים, עד שאספיק לשבת ולכתוב הכל בצורה מסודרת:


יום שני, 20 בנובמבר 2017

כיצד לתקשר בין צד c# אל צד js בתוך WebBrowser ולהיפך

פרויקט דוגמה להורדה

יש להוסיף בראש הדף (לפני המחלקה הראשונה) את הקוד הבא:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
//[ComVisibleAttribute(true)]
public partial class Form1 : Form {   ... }

בחלק Load של הדף יש להגדיר את WebBrowser ולצורך הדוגמה נכתוב בתוכו את ה-html:
private void Form1_Load(object sender, EventArgs e)
{
  // 4. Set the ObjectForScripting property in the 
      // form's constructor or a Load event handler.
      // The following code uses the form class 
      // itself for the scripting object.
      // Component Object Model (COM) must be able 
      // to access the scripting object.
      // Use [ComVisible(true)] in order to make your 
      //form visible to COM 
      // (add the ComVisibleAttribute attribute to your form class).
  webBrowser1.ObjectForScripting = this;
webBrowser1.DocumentText =
  @"<html><head>
  <script>
  // the js function to call from the c# side:
  function myFoo(arg) { alert(arg); }   </script>   </head><body>
  send code to c# side: <br/>
  <input type='text' id='snir' value='snir send to c#'></input>
  <button onclick='window.external.Test(document.getElementById('snir').value)'>
  call client C# code from javscript code</button>
  </body>
  </html>";
}


נגדיר מתודה שתקבל את המיד מצד js:
// get message from the webpage's js
[ComVisible(true)]
public void Test(string arg)
{
  MessageBox.Show(argt, "C# side");
}

נגדיר מתודה שתשלח מידע אל צד js:
private void SendToWebpage()
{
  webBrowser1.Document.InvokeScript(
    "myFoo",
    new String[] { textBox1.Text }
  );
}

יום שני, 20 במרץ 2017

איך להעתיק webbrowser ל-pictureBox ומשם לקליפבורד בעזרת בחירה

איך להעתיק webbrowser ל-pictureBox ומשם לקליפבורד בעזרת בחירה

namespace WriteBraille
{
    public partial class WebbrowserToPanel : Form
    {
        public WebbrowserToPanel()  {      InitializeComponent();   }

        private void WebbrowserToPanel_Load(object sender, EventArgs e)
        {
            webBrowser1.Url = new Uri(textBox1.Text);
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
                webBrowser1.Url = new Uri(textBox1.Text);
        }

        private Point RectStartPoint;
        private Rectangle Rect = new Rectangle();
        private Brush selectionBrush = new SolidBrush(Color.FromArgb(128, 72, 145, 220));

        private void button1_Click(object sender, EventArgs e)
        {
            Control c = webBrowser1;
            Bitmap bmp = new Bitmap(c.Width, c.Height);
            c.DrawToBitmap(bmp, c.ClientRectangle);
            pictureBox1.Image = bmp;
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            // Determine the initial rectangle coordinates...
            RectStartPoint = e.Location;
            Invalidate();
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            // Draw the rectangle...
            if (pictureBox1.Image != null)
            {
                if (Rect != null && Rect.Width > 0 && Rect.Height > 0)
                {
                    e.Graphics.FillRectangle(selectionBrush, Rect);
                }
            }
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left)
                return;
            Point tempEndPoint = e.Location;
            Rect.Location = new Point(
                Math.Min(RectStartPoint.X, tempEndPoint.X),
                Math.Min(RectStartPoint.Y, tempEndPoint.Y));
            Rect.Size = new Size(
                Math.Abs(RectStartPoint.X - tempEndPoint.X),
                Math.Abs(RectStartPoint.Y - tempEndPoint.Y));
            pictureBox1.Invalidate();
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (Rect.Contains(e.Location))
                {
                    selectionBrush.Dispose();
                    //Debug.WriteLine("Right click");
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Image img = (pictureBox1.Image as Bitmap).Clone(Rect, pictureBox1.Image.PixelFormat);
            Clipboard.SetImage(img);
        }
    }
}

יום ראשון, 25 בדצמבר 2016

יצירת תיקיה זמנית בקבצי המערכת
כאשר נעשה שימוש בקבצים שנשמרים בתור Resources של התוכנה, ויש צורך להעתיק אותם אל הכונן בשביל שימוש - תמונות למשל – קיימת כמובן האפשרות ליצור תיקיית-בת בתוך תיקיית התוכנה, אך ניתן גם לעשות שימוש נוח יותר ולפרוס את הקבצים אל תוך קבצי המערכת.
ראשית יש לשים לב להגדרות הבאות לקבצים:
-          Build Action: Embedded Resources
-          Copy To Output Directory: Do Not Copy
שלבי הביצוע:
1.   יצירת תיקיה עם שם אקראי כדי לשמור בתוכה את הקבצים
// Create a temp dirctory to save the images in:
string tempDirName = Path.Combine( Path.GetTempPath(), 
                      System.Guid.NewGuid().ToString());
Directory.CreateDirectory(tempDirName);


2.  חילוץ הקבצים מתוך האסמבלי
//Extract the images from the assembly resources
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
// You can get the images path in embedded resources by watching:
string file = myAssembly.GetManifestResourceNames()[0];


3. שמירת  כל קובץ (תמונה) בתיקיה הזמנית שיצרנו
using (Stream myStream = myAssembly.GetManifestResourceStream(file))
{
   using (Stream file_stream = File.Create(file)) {
      CopyStream(myStream, file_stream);
   }
}

private static void CopyStream(Stream input, Stream output)
{
   byte[] buffer = new byte[8 * 1024];
   int len;
   while ((len = input.Read(buffer, 0, buffer.Length)) > 0) {
      output.Write(buffer, 0, len);
   }
}

4. לא נשכח למחוק את הקבצים ביציאה מהתוכנה

private static void Form1_Closing(object sender, FormClosingEventArgs e)
{
   try {
      Directory.Delete(tempDirName, true);
   }
   catch(Exception ex) { MessageBox.Show(ex.Message); }
}