AGB  ·  Datenschutz  ·  Impressum  







Anmelden
Nützliche Links
Registrieren
Zurück Delphi-PRAXiS Programmierung allgemein Programmieren allgemein Brauche hilfe bei übersetzung von C# in ObjectPascal (.Net)
Thema durchsuchen
Ansicht
Themen-Optionen

Brauche hilfe bei übersetzung von C# in ObjectPascal (.Net)

Ein Thema von Taladan · begonnen am 13. Jul 2005 · letzter Beitrag vom 20. Jul 2005
Antwort Antwort
Seite 1 von 2  1 2      
Benutzerbild von Taladan
Taladan

Registriert seit: 5. Aug 2003
Ort: Osnabrück
505 Beiträge
 
Delphi 2005 Professional
 
#1

Brauche hilfe bei übersetzung von C# in ObjectPascal (.Net)

  Alt 13. Jul 2005, 21:39
Hallo. Ich möchte eine Klasser in .Net erstellen, die auch Hyperlinks anzeigen kann. Bisher habe ich keine entsprechende Komponente gefunden. Eine Komponente jedoch, die in C# geschrieben und auf der RichTextBox basiert, die so was kann. Leider kann ich kein C# und der Code ist für den Start doch ein wenig viel des guten.
Würde mich freuen, wenn jemand mir bei der Übersetzung hilft. Seien es nur Teile oder gar die ganze Komponente.

Hier die C# Datei:
Delphi-Quellcode:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace RichTextBoxLinks
{
   public class RichTextBoxEx : RichTextBox
   {
      #region Interop-Defines
      [ StructLayout( LayoutKind.Sequential )]
      private struct CHARFORMAT2_STRUCT
      {
         public UInt32   cbSize;
         public UInt32  dwMask;
         public UInt32  dwEffects;
         public Int32    yHeight;
         public Int32    yOffset;
         public Int32   crTextColor;
         public byte    bCharSet;
         public byte    bPitchAndFamily;
         [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
         public char[]  szFaceName;
         public UInt16   wWeight;
         public UInt16   sSpacing;
         public int      crBackColor; // Color.ToArgb() -> int
         public int      lcid;
         public int      dwReserved;
         public Int16   sStyle;
         public Int16   wKerning;
         public byte      bUnderlineType;
         public byte      bAnimation;
         public byte      bRevAuthor;
         public byte      bReserved1;
      }


      [DllImport("user32.dll", CharSet=CharSet.Auto)]
      private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

      private const int WM_USER          = 0x0400;
      private const int EM_GETCHARFORMAT    = WM_USER+58;
      private const int EM_SETCHARFORMAT    = WM_USER+68;

      private const int SCF_SELECTION   = 0x0001;
      private const int SCF_WORD      = 0x0002;
      private const int SCF_ALL      = 0x0004;

      #region CHARFORMAT2 Flags
      private const UInt32 CFE_BOLD      = 0x0001;
      private const UInt32 CFE_ITALIC      = 0x0002;
      private const UInt32 CFE_UNDERLINE   = 0x0004;
      private const UInt32 CFE_STRIKEOUT   = 0x0008;
      private const UInt32 CFE_PROTECTED   = 0x0010;
      private const UInt32 CFE_LINK      = 0x0020;
      private const UInt32 CFE_AUTOCOLOR   = 0x40000000;
      private const UInt32 CFE_SUBSCRIPT   = 0x00010000;      /* Superscript and subscript are */
      private const UInt32 CFE_SUPERSCRIPT= 0x00020000;      /* mutually exclusive          */

      private const int CFM_SMALLCAPS      = 0x0040;         /* (*)   */
      private const int CFM_ALLCAPS      = 0x0080;         /* Displayed by 3.0   */
      private const int CFM_HIDDEN      = 0x0100;         /* Hidden by 3.0 */
      private const int CFM_OUTLINE      = 0x0200;         /* (*)
   */
      private const int CFM_SHADOW      = 0x0400;         /* (*)   */
      private const int CFM_EMBOSS      = 0x0800;         /* (*)
   */
      private const int CFM_IMPRINT      = 0x1000;         /* (*)   */
      private const int CFM_DISABLED      = 0x2000;
      private const int CFM_REVISED      = 0x4000;

      private const int CFM_BACKCOLOR      = 0x04000000;
      private const int CFM_LCID         = 0x02000000;
      private const int CFM_UNDERLINETYPE   = 0x00800000;      /* Many displayed by 3.0 */
      private const int CFM_WEIGHT      = 0x00400000;
      private const int CFM_SPACING      = 0x00200000;      /* Displayed by 3.0   */
      private const int CFM_KERNING      = 0x00100000;      /* (*)
   */
      private const int CFM_STYLE         = 0x00080000;      /* (*)   */
      private const int CFM_ANIMATION      = 0x00040000;      /* (*)
   */
      private const int CFM_REVAUTHOR      = 0x00008000;


      private const UInt32 CFM_BOLD      = 0x00000001;
      private const UInt32 CFM_ITALIC      = 0x00000002;
      private const UInt32 CFM_UNDERLINE   = 0x00000004;
      private const UInt32 CFM_STRIKEOUT   = 0x00000008;
      private const UInt32 CFM_PROTECTED   = 0x00000010;
      private const UInt32 CFM_LINK      = 0x00000020;
      private const UInt32 CFM_SIZE      = 0x80000000;
      private const UInt32 CFM_COLOR      = 0x40000000;
      private const UInt32 CFM_FACE      = 0x20000000;
      private const UInt32 CFM_OFFSET      = 0x10000000;
      private const UInt32 CFM_CHARSET   = 0x08000000;
      private const UInt32 CFM_SUBSCRIPT   = CFE_SUBSCRIPT | CFE_SUPERSCRIPT;
      private const UInt32 CFM_SUPERSCRIPT= CFM_SUBSCRIPT;

      private const byte CFU_UNDERLINENONE      = 0x00000000;
      private const byte CFU_UNDERLINE         = 0x00000001;
      private const byte CFU_UNDERLINEWORD      = 0x00000002; /* (*) displayed as ordinary underline   */
      private const byte CFU_UNDERLINEDOUBLE      = 0x00000003; /* (*)
 displayed as ordinary underline   */
      private const byte CFU_UNDERLINEDOTTED      = 0x00000004;
      private const byte CFU_UNDERLINEDASH      = 0x00000005;
      private const byte CFU_UNDERLINEDASHDOT      = 0x00000006;
      private const byte CFU_UNDERLINEDASHDOTDOT   = 0x00000007;
      private const byte CFU_UNDERLINEWAVE      = 0x00000008;
      private const byte CFU_UNDERLINETHICK      = 0x00000009;
      private const byte CFU_UNDERLINEHAIRLINE   = 0x0000000A; /* (*) displayed as ordinary underline   */

      #endregion

      #endregion

      public RichTextBoxEx()
      {
         // Otherwise, non-standard links get lost when user starts typing
         // next to a non-standard link
         this.DetectUrls = false;
      }

      [DefaultValue(false)]
      public new bool DetectUrls
      {
         get { return base.DetectUrls; }
         set { base.DetectUrls = value; }
      }

      /// <summary>
      /// Insert a given text as a link into the RichTextBox at the current insert position.
      /// </summary>
      /// <param name="text">Text to be inserted</param>
      public void InsertLink(string text)
      {
         InsertLink(text, this.SelectionStart);
      }

      /// <summary>
      /// Insert a given text at a given position as a link.
      /// </summary>
      /// <param name="text">Text to be inserted</param>
      /// <param name="position">Insert position</param>
      public void InsertLink(string text, int position)
      {
         if (position < 0 || position > this.Text.Length)
            throw new ArgumentOutOfRangeException("position");

         this.SelectionStart = position;
         this.SelectedText = text;
         this.Select(position, text.Length);
         this.SetSelectionLink(true);
         this.Select(position + text.Length, 0);
      }
      
      /// <summary>
      /// Insert a given text at at the current input position as a link.
      /// The link text is followed by a hash (#) and the given hyperlink text, both of
      /// them invisible.
      /// When clicked on, the whole link text and hyperlink string are given in the
      /// LinkClickedEventArgs.
      /// </summary>
      /// <param name="text">Text to be inserted</param>
      /// <param name="hyperlink">Invisible hyperlink string to be inserted</param>
      public void InsertLink(string text, string hyperlink)
      {
         InsertLink(text, hyperlink, this.SelectionStart);
      }

      /// <summary>
      /// Insert a given text at a given position as a link. The link text is followed by
      /// a hash (#) and the given hyperlink text, both of them invisible.
      /// When clicked on, the whole link text and hyperlink string are given in the
      /// LinkClickedEventArgs.
      /// </summary>
      /// <param name="text">Text to be inserted</param>
      /// <param name="hyperlink">Invisible hyperlink string to be inserted</param>
      /// <param name="position">Insert position</param>
      public void InsertLink(string text, string hyperlink, int position)
      {
         if (position < 0 || position > this.Text.Length)
            throw new ArgumentOutOfRangeException("position");

         this.SelectionStart = position;
         this.SelectedRtf = @"{\rtf1\ansi "+text+@"\v #"+hyperlink+@"\v0}";
         this.Select(position, text.Length + hyperlink.Length + 1);
         this.SetSelectionLink(true);
         this.Select(position + text.Length + hyperlink.Length + 1, 0);
      }

      /// <summary>
      /// Set the current selection's link style
      /// </summary>
      /// <param name="link">true: set link style, false: clear link style</param>
      public void SetSelectionLink(bool link)
      {
         SetSelectionStyle(CFM_LINK, link ? CFE_LINK : 0);
      }
      /// <summary>
      /// Get the link style for the current selection
      /// </summary>
      /// <returns>0: link style not set, 1: link style set, -1: mixed</returns>
      public int GetSelectionLink()
      {
         return GetSelectionStyle(CFM_LINK, CFE_LINK);
      }


      private void SetSelectionStyle(UInt32 mask, UInt32 effect)
      {
         CHARFORMAT2_STRUCT cf = new CHARFORMAT2_STRUCT();
         cf.cbSize = (UInt32)Marshal.SizeOf(cf);
         cf.dwMask = mask;
         cf.dwEffects = effect;

         IntPtr wpar = new IntPtr(SCF_SELECTION);
         IntPtr lpar = Marshal.AllocCoTaskMem( Marshal.SizeOf( cf ) );
         Marshal.StructureToPtr(cf, lpar, false);

         IntPtr res = SendMessage(Handle, EM_SETCHARFORMAT, wpar, lpar);

         Marshal.FreeCoTaskMem(lpar);
      }

      private int GetSelectionStyle(UInt32 mask, UInt32 effect)
      {
         CHARFORMAT2_STRUCT cf = new CHARFORMAT2_STRUCT();
         cf.cbSize = (UInt32)Marshal.SizeOf(cf);
         cf.szFaceName = new char[32];

         IntPtr wpar = new IntPtr(SCF_SELECTION);
         IntPtr lpar =    Marshal.AllocCoTaskMem( Marshal.SizeOf( cf ) );
         Marshal.StructureToPtr(cf, lpar, false);

         IntPtr res = SendMessage(Handle, EM_GETCHARFORMAT, wpar, lpar);

         cf = (CHARFORMAT2_STRUCT)Marshal.PtrToStructure(lpar, typeof(CHARFORMAT2_STRUCT));

         int state;
         // dwMask holds the information which properties are consistent throughout the selection:
         if ((cf.dwMask & mask) == mask)
         {
            if ((cf.dwEffects & effect) == effect)
               state = 1;
            else
               state = 0;
         }
         else
         {
            state = -1;
         }
         
         Marshal.FreeCoTaskMem(lpar);
         return state;
      }
   }
}
Und hier meine bisherige Übersetzung:
Delphi-Quellcode:
unit RichBoxHyperlink;

interface

uses
  System.Drawing, System.Collections, System.ComponentModel, System.Windows.Forms,
  System.Runtime.InteropServices;


type
   charformat2 = class
   private
    cbSize : System.UInt32;
    dwMask : System.UInt32;
    dwEffects : System.UInt32;
    yHeight : System.Int32;
    yOffset : System.Int32;
      crTextColor : System.Int32;
      bCharSet : system.Byte;
      bPitchAndFamily : system.Byte;
     [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
     szFaceName : system.Char;
    wWeight : system.UInt16;
    sSpacing : System.UInt16;
      crBackColor : System.Int32; // Color.ToArgb() -> int
      lcid : System.Int32;
      dwReserved : System.Int32;
    sStyle : System.Int16;
    wKerning : System.Int16;
    bUnderlineType : System.Byte;
    bAnimation : System.Byte;
    bRevAuthor : System.Byte;
    bReserved1 : System.Byte;
   end;


  TRichBoxHyperlink = class(System.Windows.Forms.Richtextbox)
  {$REGION 'Vom Designer verwalteter Code'}
  strict private
    /// <summary>
    /// Erforderliche Designervariable.
    /// </summary>
    Components: System.ComponentModel.Container;
    /// <summary>
    /// Erforderliche Methode zur Unterstützung des Designers -
    /// ändern Sie die Methode nicht mit dem Quelltext-Editor
    /// </summary>
    procedure InitializeComponent;
  {$ENDREGION}
  strict protected
    /// <summary>
    /// Ressourcen nach der Verwendung bereinigen
    /// </summary>
    procedure Dispose(Disposing: Boolean); override;
  private
    { Private-Deklarationen }
    FDetectUrls : boolean;
    const WM_User : System.int32 = 32;
    function get_urls : boolean ;
    procedure set_urls(Value : boolean);

  public
    constructor Create; overload;
    constructor Create(Container: System.ComponentModel.IContainer); overload;
    procedure InsertLink(text : String); overload;
    procedure InsertLink(text : String; position : Integer); overload;
  published
    property DetectUrls : boolean read get_urls write set_urls default false;
  end;



implementation

uses
  System.Globalization;

{$AUTOBOX ON}

{$REGION 'Vom Windows Form-Designer erzeugter Code'}
/// <summary>
/// Erforderliche Methode zur Unterstützung des Designers -
/// ändern Sie die Methode nicht mit dem Quelltext-Editor
/// </summary>

procedure TRichBoxHyperlink.InitializeComponent;
begin
  Self.Components := System.ComponentModel.Container.Create;
end;

{$ENDREGION}

function TRichBoxHyperlink.get_urls : boolean;
begin
  result := FDetectUrls;
end;

procedure TRichBoxHyperlink.InsertLink(text : String);
begin
  InsertLink(Text, Self.SelectionStart);
end;


procedure TRichBoxHyperlink.InsertLink(text : String; position : Integer);
begin
  if (Position < 0) or (Position > self.Text.Length) then ArgumentOutOfRangeException.Create('Position') else
  begin
//         self.SelectionStart := position;
//         self.SelectedText := text;
//         self.Select(position, text.Length);
//         self.SetSelectionLink(true);
//         self.Select(position + text.Length, 0);
  end;
end;


procedure TRichBoxHyperlink.set_urls(Value : boolean);
begin
  FDetectUrls := Value;
end;

constructor TRichBoxHyperlink.Create;
begin
  inherited Create;
  //
  // Erforderlich für die Unterstützung des Windows Forms-Designers
  //
  InitializeComponent;
  //
  // TODO: Fügen Sie nach dem Aufruf von InitializeComponent Konstruktorcode hinzu.
  //
end;

constructor TRichBoxHyperlink.Create(Container: System.ComponentModel.IContainer);
begin
  inherited Create;
  //
  // Erforderlich für die Unterstützung des Windows Forms-Designers
  //
  Container.Add(Self);
  InitializeComponent;
  //
  // TODO: Fügen Sie nach dem Aufruf von InitializeComponent Konstruktorcode hinzu.
  //
end;

procedure TRichBoxHyperlink.Dispose(Disposing: Boolean);
begin
  if Disposing then
  begin
    if Components <> nil then
      Components.Dispose();
  end;
  inherited Dispose(Disposing);
end;

end.
Und beide Dateien als Anhang
Angehängte Dateien
Dateityp: pas richboxhyperlink_115.pas (4,0 KB, 0x aufgerufen)
Marco
Wer Rechtschreibfehler findet, der darf sie behalten

Carpe Diem - Nutze den Tag (und zwar den ganzen!)
  Mit Zitat antworten Zitat
Benutzerbild von Taladan
Taladan

Registriert seit: 5. Aug 2003
Ort: Osnabrück
505 Beiträge
 
Delphi 2005 Professional
 
#2

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 13. Jul 2005, 21:48
PS: Mir würde es schon reichen, wenn mir jemand sagt, wie ich die C# Komponente mit Delphi ans laufen bekomme.
Marco
Wer Rechtschreibfehler findet, der darf sie behalten

Carpe Diem - Nutze den Tag (und zwar den ganzen!)
  Mit Zitat antworten Zitat
Benutzerbild von Speedmaster
Speedmaster

Registriert seit: 4. Mär 2005
Ort: Karlsruhe
535 Beiträge
 
Delphi 2005 Personal
 
#3

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 13. Jul 2005, 22:16
Zitat von Taladan:
PS: Mir würde es schon reichen, wenn mir jemand sagt, wie ich die C# Komponente mit Delphi ans laufen bekomme.
Das wird vermutlich nicht möglich sein, das sind WinForms Komponente oder?
Felix K.
Zitat:
Siehst du diesen Park da unten?
Jeden Tag lernen sich leute kennen und verlassen einander, und du hast dein ganzes Leben Zeit darin zu gehen!
  Mit Zitat antworten Zitat
Benutzerbild von Luckie
Luckie

Registriert seit: 29. Mai 2002
37.621 Beiträge
 
Delphi 2006 Professional
 
#4

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 13. Jul 2005, 22:20
In Delphi 2005 kann man doch C# Assemblies auch in einem Projekt mit Delphi für -NET nutzen oder irre ich da?
Michael
Ein Teil meines Codes würde euch verunsichern.
  Mit Zitat antworten Zitat
Robert_G
(Gast)

n/a Beiträge
 
#5

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 14. Jul 2005, 00:20
Zitat von Luckie:
In Delphi 2005 kann man doch C# Assemblies auch in einem Projekt mit Delphi für -NET nutzen oder irre ich da?
Konnte man auch schon in D8.
@Taladan
Nehme den C# - Code packe ihn in eine neue C# Assembly und kompiliere diese.
Die Assembly kannst du dann ganz easy in D.Net benutzen.

Nachtrag:
Man sollte C++'lern dringend einen Kurs in C# geben. Pfui deivel *sich schüttelt*
Ich habe mal einfach alle Konstanten rausgelöscht, die nicht verwendet werden (also 99% davon ).
Nun solltest du es entziffern können.

btw: ein struct in C# ist ein value type und somit ein record in Pascal.

Code:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace DP.RichTextEx
{
    public class RichTextBoxEx : RichTextBox
    {
        #region Interop-Defines

        [StructLayout(LayoutKind.Sequential)]
        struct CharFormat2
        {
            public uint cbSize;

            /// <summary>
            /// dwMask holds the information which properties are consistent
            /// throughout the selection
            /// </summary>
            public CharFormat2Mask dwMask;

            public CharFormat2Effect dwEffects;

            public int yHeight;
            public int yOffset;
            public int crTextColor;
            public byte bCharSet;
            public byte bPitchAndFamily;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
            public char[] szFaceName;

            public ushort wWeight;
            public ushort sSpacing;

            /// <summary>
            /// Color.ToArgb() -> int
            /// </summary>
            public int crBackColor;

            public int lcid;
            public int dwReserved;
            public short sStyle;
            public short wKerning;
            public byte bUnderlineType;
            public byte bAnimation;
            public byte bRevAuthor;
            public byte bReserved1;
        }

        [DllImport("user32.dll", CharSet=CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd,
                                         Message msg,
                                         IntPtr wParam,
                                         IntPtr lParam);

        enum Message :int
        {
            User = 0x0400,
            /// <summary>
            /// determines the current character formatting in a rich edit control.
            /// </summary>
            GetCharFormat = User + 58,
            /// <summary>
            /// sets character formatting in a rich edit control.
            /// </summary>
            SetCharFormat = User + 68
        }

        /// <summary>
        /// Applies the formatting to the current selection. If the selection is empty,
        /// the character formatting is applied to the insertion point,
        /// and the new character format is in effect only until the insertion point changes.
        /// </summary>
        const int SCF_SELECTION = 0x0001;

        #region CHARFORMAT2 Flags

        enum CharFormat2Effect :uint
        {
            /// <summary>
            /// A rich edit control can send EN_LINK notification messages when it receives mouse messages
            ///  while the mouse pointer is over text with the <see cref="CharFormat2Effect.Link">CFE_LINK</see> effect.
            /// </summary>
            Link = 0x0020,
            None = 0
        }

        enum CharFormat2Mask :uint
        {
            /// <summary>
            /// Indicates the <see cref="CharFormat2Effect.Link">CFE_LINK</see> value is valid.
            /// </summary>
            Link = 0x00000020
        }

        #endregion

        #endregion

        public
            RichTextBoxEx()
        {
            // Otherwise, non-standard links get lost when user starts typing
            // next to a non-standard link
            this.DetectUrls = false;
        }

        [DefaultValue(false)]
        new public
            bool DetectUrls
        {
            get { return base.DetectUrls; }
            set { base.DetectUrls = value; }
        }

        /// <summary>
        /// Insert a given text as a link into the RichTextBox at the current insert position.
        /// </summary>
        /// <param name="text">Text to be inserted</param>
        public void InsertLink(string text)
        {
            InsertLink(text, this.SelectionStart);
        }

        /// <summary>
        /// Insert a given text at a given position as a link.
        /// </summary>
        /// <param name="text">Text to be inserted</param>
        /// <param name="position">Insert position</param>
        public void InsertLink(string text, int position)
        {
            if (position < 0 || position > this.Text.Length)
            {
                throw new ArgumentOutOfRangeException("position");
            }

            this.SelectionStart = position;
            this.SelectedText = text;
            this.Select(position, text.Length);
            this.SetSelectionLink(true);
            this.Select(position + text.Length, 0);
        }

        /// <summary>
        /// Insert a given text at at the current input position as a link.
        /// The link text is followed by a hash (#) and the given hyperlink text, both of
        /// them invisible.
        /// When clicked on, the whole link text and hyperlink string are given in the
        /// LinkClickedEventArgs.
        /// </summary>
        /// <param name="text">Text to be inserted</param>
        /// <param name="hyperlink">Invisible hyperlink string to be inserted</param>
        public void InsertLink(string text, string hyperlink)
        {
            InsertLink(text, hyperlink, this.SelectionStart);
        }

        /// <summary>
        /// Insert a given text at a given position as a link. The link text is followed by
        /// a hash (#) and the given hyperlink text, both of them invisible.
        /// When clicked on, the whole link text and hyperlink string are given in the
        /// LinkClickedEventArgs.
        /// </summary>
        /// <param name="text">Text to be inserted</param>
        /// <param name="hyperlink">Invisible hyperlink string to be inserted</param>
        /// <param name="position">Insert position</param>
        public void InsertLink(string text, string hyperlink, int position)
        {
            if (position < 0 || position > this.Text.Length)
            {
                throw new ArgumentOutOfRangeException("position");
            }

            this.SelectionStart = position;
            this.SelectedRtf = @"{\rtf1\ansi " + text + @"\v #" + hyperlink + @"\v0}";
            this.Select(position, text.Length + hyperlink.Length + 1);
            this.SetSelectionLink(true);
            this.Select(position + text.Length + hyperlink.Length + 1, 0);
        }

        /// <summary>
        /// Set the current selection's link style
        /// </summary>
        /// <param name="link">true: set link style, false: clear link style</param>
        public void SetSelectionLink(bool link)
        {
            SetSelectionStyle(CharFormat2Mask.Link, link ? CharFormat2Effect.Link : CharFormat2Effect.None);
        }

        /// <summary>
        /// Get the link style for the current selection
        /// </summary>
        /// <returns>0: link style not set, 1: link style set, -1: mixed</returns>
        public int GetSelectionLink()
        {
            return GetSelectionStyle(CharFormat2Mask.Link, CharFormat2Effect.Link);
        }

        void SetSelectionStyle(CharFormat2Mask mask, CharFormat2Effect effect)
        {
            CharFormat2 cf = new CharFormat2();
            cf.cbSize = (uint) Marshal.SizeOf(cf);
            cf.dwMask = mask;
            cf.dwEffects = effect;

            IntPtr wpar = new IntPtr(SCF_SELECTION);
            IntPtr lpar = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf));
            Marshal.StructureToPtr(cf, lpar, false);

            SendMessage(Handle, Message.SetCharFormat, wpar, lpar);

            Marshal.FreeCoTaskMem(lpar);
        }

        int GetSelectionStyle(CharFormat2Mask mask, CharFormat2Effect effect)
        {
            CharFormat2 cf = new CharFormat2();
            cf.cbSize = (uint) Marshal.SizeOf(cf);
            cf.szFaceName = new char[32];

            IntPtr wpar = new IntPtr(SCF_SELECTION);
            IntPtr lpar = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf));
            Marshal.StructureToPtr(cf, lpar, false);

            SendMessage(Handle, Message.GetCharFormat, wpar, lpar);

            cf = (CharFormat2) Marshal.PtrToStructure(lpar, typeof (CharFormat2));

            int state;
            if ((cf.dwMask & mask) == mask)
            {
                if ((cf.dwEffects & effect) == effect)
                {
                    state = 1;
                } else
                {
                    state = 0;
                }
            } else
            {
                state = -1;
            }

            Marshal.FreeCoTaskMem(lpar);
            return state;
        }
    }
}
Nachtrag: Im Anhang ist die kompilierte Assembly. Du kannst es einfach direkt so verwenden, oder mit Hilfe des Reflectors den Code zu D.Net übersetzen.
Angehängte Dateien
Dateityp: zip dp.richtextex_102.zip (4,0 KB, 6x aufgerufen)
  Mit Zitat antworten Zitat
Benutzerbild von Taladan
Taladan

Registriert seit: 5. Aug 2003
Ort: Osnabrück
505 Beiträge
 
Delphi 2005 Professional
 
#6

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 14. Jul 2005, 15:01
Zitat von Robert_G:
Nachtrag: Im Anhang ist die kompilierte Assembly. Du kannst es einfach direkt so verwenden, oder mit Hilfe des Reflectors den Code zu D.Net übersetzen.
Das hab ich getan, dabei kam aber ein ähm doch recht seltsamer Code heraus. Der so gar nicht funktionieren kann, denke ich.

Delphi-Quellcode:
unit DP.RichTextEx;
interface
type
public RichTextBoxEx = class(RichTextBox)
      // Methods
      public constructor Create;
      public function GetSelectionLink: Integer;
      strict private function GetSelectionStyle(mask: CharFormat2Mask; effect: CharFormat2Effect): Integer;
      public procedure InsertLink(text: string);
      public procedure InsertLink(text: string; position: Integer);
      public procedure InsertLink(text: string; hyperlink: string);
      public procedure InsertLink(text: string; hyperlink: string; position: Integer);
      [DllImport('user32.dll', CharSet=CharSet.Auto)]
      strict private class extern function SendMessage(hWnd: IntPtr; msg: Message; wParam: IntPtr; lParam: IntPtr): IntPtr; static;
      public procedure SetSelectionLink(link: boolean);
      strict private procedure SetSelectionStyle(mask: CharFormat2Mask; effect: CharFormat2Effect);

      // Properties
      [DefaultValue(false)]
      public property DetectUrls: boolean read get_DetectUrls write set_DetectUrls;

      // Fields
      strict private const SCF_SELECTION: Integer = 1;

      type // Nested Types
            [StructLayout(LayoutKind.Sequential)]
            strict private CharFormat2 = record
                  // Fields
                  public bAnimation: Byte;
                  public bCharSet: Byte;
                  public bPitchAndFamily: Byte;
                  public bReserved1: Byte;
                  public bRevAuthor: Byte;
                  public bUnderlineType: Byte;
                  public cbSize: Cardinal;
                  public crBackColor: Integer;
                  public crTextColor: Integer;
                  public dwEffects: CharFormat2Effect;
                  public dwMask: CharFormat2Mask;
                  public dwReserved: Integer;
                  public lcid: Integer;
                  public sSpacing: Word;
                  public sStyle: Smallint;
                  [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
                  public szFaceName: Char[];
                  public wKerning: Smallint;
                  public wWeight: Word;
                  public yHeight: Integer;
                  public yOffset: Integer;

            end;

            strict private CharFormat2Effect = (Link=32, None=0);
            strict private CharFormat2Mask = (Link=32);
            strict private Message = (GetCharFormat=1082, SetCharFormat=1092, User=1024);

end;
implementation
end.
Den habe ich ein wenig umstruktoriert und bis jetzt kam dieses heraus:
Delphi-Quellcode:
unit RichBoxHyperlink;

interface

uses
  System.Drawing, System.Collections, System.ComponentModel, System.Windows.Forms,
  System.Runtime.InteropServices;

type
   charformat2 = record
    bAnimation : System.Byte;
      bCharSet : system.Byte;
      bPitchAndFamily : system.Byte;
    bReserved1 : System.Byte;
    bRevAuthor: Byte;
    bUnderlineType : System.Byte;
    cbSize: Cardinal;
      crBackColor : integer;
      crTextColor : integer;
// dwEffects: CharFormat2Effect;
// dwMask: CharFormat2Mask;
      dwReserved : integer;
      lcid : integer;
    sSpacing : word;
    sStyle : Smallint;
     [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
     szFaceName : system.Char;
    wKerning : Smallint;
    wWeight : Smallint;
    yHeight : integer;
    yOffset : integer;
   end;


  TRichBoxHyperlink = class(System.Windows.Forms.Richtextbox)
  {$REGION 'Vom Designer verwalteter Code'}
  strict private
    /// <summary>
    /// Erforderliche Designervariable.
    /// </summary>
    Components: System.ComponentModel.Container;
    /// <summary>
    /// Erforderliche Methode zur Unterstützung des Designers -
    /// ändern Sie die Methode nicht mit dem Quelltext-Editor
    /// </summary>
    procedure InitializeComponent;
  {$ENDREGION}
  strict protected
    /// <summary>
    /// Ressourcen nach der Verwendung bereinigen
    /// </summary>
    procedure Dispose(Disposing: Boolean); override;
  private
    { Private-Deklarationen }
    FDetectUrls : boolean;
    function get_urls : boolean ;
    procedure set_urls(Value : boolean);

  public
    constructor Create; overload;
    constructor Create(Container: System.ComponentModel.IContainer); overload;
    procedure InsertLink(text : String); overload;
    procedure InsertLink(text : String; position : Integer); overload;
  published
    property DetectUrls : boolean read get_urls write set_urls default false;
  end;



implementation

uses
  System.Globalization;

{$AUTOBOX ON}

{$REGION 'Vom Windows Form-Designer erzeugter Code'}
/// <summary>
/// Erforderliche Methode zur Unterstützung des Designers -
/// ändern Sie die Methode nicht mit dem Quelltext-Editor
/// </summary>

procedure TRichBoxHyperlink.InitializeComponent;
begin
  Self.Components := System.ComponentModel.Container.Create;
end;

{$ENDREGION}

function TRichBoxHyperlink.get_urls : boolean;
begin
  result := FDetectUrls;
end;

procedure TRichBoxHyperlink.InsertLink(text : String);
begin
  InsertLink(Text, Self.SelectionStart);
end;


procedure TRichBoxHyperlink.InsertLink(text : String; position : Integer);
begin
  if (Position < 0) or (Position > self.Text.Length) then ArgumentOutOfRangeException.Create('Position') else
  begin
//         self.SelectionStart := position;
//         self.SelectedText := text;
//         self.Select(position, text.Length);
//         self.SetSelectionLink(true);
//         self.Select(position + text.Length, 0);
  end;
end;


procedure TRichBoxHyperlink.set_urls(Value : boolean);
begin
  FDetectUrls := Value;
end;

constructor TRichBoxHyperlink.Create;
begin
  inherited Create;
  //
  // Erforderlich für die Unterstützung des Windows Forms-Designers
  //
  InitializeComponent;
  //
  // TODO: Fügen Sie nach dem Aufruf von InitializeComponent Konstruktorcode hinzu.
  //
end;

constructor TRichBoxHyperlink.Create(Container: System.ComponentModel.IContainer);
begin
  inherited Create;
  //
  // Erforderlich für die Unterstützung des Windows Forms-Designers
  //
  Container.Add(Self);
  InitializeComponent;
  //
  // TODO: Fügen Sie nach dem Aufruf von InitializeComponent Konstruktorcode hinzu.
  //
end;

procedure TRichBoxHyperlink.Dispose(Disposing: Boolean);
begin
  if Disposing then
  begin
    if Components <> nil then
      Components.Dispose();
  end;
  inherited Dispose(Disposing);
end;

end.
Was ich nur überhaupt nicht zuordnen kann, und damit die Übersetzung übersetzten sind diese Zeilen:
Zitat:
strict private class extern function SendMessage(hWnd: IntPtr; msg: Message; wParam: IntPtr; lParam: IntPtr): IntPtr; static;

strict private CharFormat2Effect = (Link=32, None=0);

strict private CharFormat2Mask = (Link=32);

strict private Message = (GetCharFormat=1082, SetCharFormat=1092, User=1024);
PS: Ich habe mir vorgenommen die Komponente nicht nur zu verwenden, sondern möglichst auch zu verstehen, was ich verwende... (hoffentlich klappt das)
Marco
Wer Rechtschreibfehler findet, der darf sie behalten

Carpe Diem - Nutze den Tag (und zwar den ganzen!)
  Mit Zitat antworten Zitat
Robert_G
(Gast)

n/a Beiträge
 
#7

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 14. Jul 2005, 20:15
Zitat von Taladan:
PS: Ich habe mir vorgenommen die Komponente nicht nur zu verwenden, sondern möglichst auch zu verstehen, was ich verwende... (hoffentlich klappt das)
Guter Vorsatz! Du solltest aber flexibler im Umgang mit dem MSDN, der .Net OH und der spachreferenz von D.Net sein.

Zitat von Taladan:
Was ich nur überhaupt nicht zuordnen kann, und damit die Übersetzung übersetzten sind diese Zeilen:
Na dann...

strict private class extern function SendMessage(hWnd: IntPtr; msg: Message; wParam: IntPtr; lParam: IntPtr): IntPtr; static; Das ist die Deklaration einer externen Funktion. also einer, die nicht durch .Net sondern von einer Win32 DLL bereitgestellt wird.

Delphi-Quellcode:
strict private CharFormat2Effect = (Link=32, None=0);
strict private CharFormat2Mask = (Link=32);
strict private Message = (GetCharFormat=1082, SetCharFormat=1092, User=1024);
Das sind Aufzählungstypen ähnlich zu denen aus Delphi32.
Ich halte es in den meisten Fällen für eine schlechte Idee in .Net normale numerische Konstanten zu verwenden.
Erstens müllt man sich schnell mit kryptischen Bezweichnern zu und zweitens sind Auzählungen type safe.
Du kannst einer Variable vom Typ Message nur Werte vom Typ Message zuweisen, aber du kannst einen Message-Wert immer von<->zu seinem Basistypen umwandeln. (hier der Standardtyp für Aufzählungen: Integer/Int32)
Da Aufzählungen zur Laufzeit exakt das gleiche Verhalten wie eine numerische Konstante haben gibt es keinerlei Nachteile.
Ich hatte die Deklaration von SendMessage so geändert, dass es msg vom Typen Message schluckt.
Der Marshaler wird es automatisch als richtigen numerischen Wert behandeln, aber zur compilezeit bekommst du einen Fehler, wenn du einen anderen (hier sinnlosen) Wert zuweisen willst.
Möglich sind hier also nur die 3 Werte:
Delphi-Quellcode:
Message.GetCharFormat
Message.GetCharFormat
Message.User
Ich hoffe das half etwas weiter...
  Mit Zitat antworten Zitat
Benutzerbild von MaBuSE
MaBuSE

Registriert seit: 23. Sep 2002
Ort: Frankfurt am Main (in der Nähe)
1.837 Beiträge
 
Delphi 10 Seattle Enterprise
 
#8

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 14. Jul 2005, 20:29
Zitat von Taladan:
Hallo. Ich möchte eine Klasser in .Net erstellen, die auch Hyperlinks anzeigen kann. Bisher habe ich keine entsprechende Komponente gefunden. Eine Komponente jedoch, die in C# geschrieben und auf der RichTextBox basiert, die so was kann. Leider kann ich kein C# und der Code ist für den Start doch ein wenig viel des guten.
Würde mich freuen, wenn jemand mir bei der Übersetzung hilft. Seien es nur Teile oder gar die ganze Komponente.
Warum denkt den niemand an den BabelCode ?

Es gibt einen sehr interesannten Artikel dazu im BDN.
Das Ganze wurde auch von Ua und Magin auf den Delphi Tagen in Kassel gezeigt.

BDN Artikel - BabelCode - C# to Delphi Converter (A tale of two CodeDOMs)

Hier ist der BabelCode direkt zum Ausprobieren !!!

Man gibt ihm etwas C# Code und er macht Delphi .net Code daraus.
OK er ist nicht perfekt, manche "Spezialitäten" kann er noch nicht übersetzen, aber das ist dann schon mal ein solider Grundstock auf dem man aufsetzen kann.

Ich hoffe diese Info hilft Euch weiter

----------schnipp---------------------------------

Hier ist der generierte Code:
[edit]
Den langen Code, durch den gekürzten von Robert_G ersetzt
[/edit]

Delphi-Quellcode:
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.573
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------

unit DP.RichTextEx;

interface

type
  RichTextBoxEx = class(RichTextBox)
  public
  type
    CharFormat2Mask = (Link);
    CharFormat2Effect = (_Link, None);
    TArrayOfWideChar = array of WideChar;
    [StructLayout(LayoutKind.Sequential)]
    CharFormat2 = class
    public
      cbSize: Cardinal;
      dwMask: CharFormat2Mask;
      dwEffects: CharFormat2Effect;
      yHeight: Integer;
      yOffset: Integer;
      crTextColor: Integer;
      bCharSet: Byte;
      bPitchAndFamily: Byte;
      szFaceName: TArrayOfWideChar;
      wWeight: System.UInt16;
      sSpacing: System.UInt16;
      crBackColor: Integer;
      lcid: Integer;
      dwReserved: Integer;
      sStyle: SmallInt;
      wKerning: SmallInt;
      bUnderlineType: Byte;
      bAnimation: Byte;
      bRevAuthor: Byte;
      bReserved1: Byte;
    end;
    
    Message = (User, GetCharFormat, SetCharFormat);
  strict private
    SCF_SELECTION: Integer;
  public
    constructor Create;
    function get_DetectUrls: Boolean; reintroduce;
    procedure set_DetectUrls(Value: Boolean); reintroduce;
    [DefaultValue(False)]
    property DetectUrls: Boolean read get_DetectUrls write set_DetectUrls;
  strict private
    [DllImport('user32.dll', CharSet=CharSet.Auto)]
    class function SendMessage(hWnd: IntPtr; msg: Message; wParam: IntPtr; lParam: IntPtr): IntPtr;static;
  public
    procedure InsertLink(text: string); overload;
    procedure InsertLink(text: string; position: Integer); overload;
    procedure InsertLink(text: string; hyperlink: string); overload;
    procedure InsertLink(text: string; hyperlink: string; position: Integer); overload;
    procedure SetSelectionLink(_link: Boolean);
    function GetSelectionLink: Integer;
  strict private
    procedure SetSelectionStyle(mask: CharFormat2Mask; effect: CharFormat2Effect);
    function GetSelectionStyle(mask: CharFormat2Mask; effect: CharFormat2Effect): Integer;
  end;
  
implementation

{$AUTOBOX ON}
{$HINTS OFF}
{$WARNINGS OFF}

constructor RichTextBoxEx.Create;
begin
  inherited Create;
  Self.DetectUrls := False;
end;

function RichTextBoxEx.get_DetectUrls: Boolean;
begin
  Result := inherited DetectUrls;
end;

procedure RichTextBoxEx.set_DetectUrls(Value: Boolean);
begin
  inherited DetectUrls := value;
end;

class function RichTextBoxEx.SendMessage(hWnd: IntPtr; msg: Message; wParam: IntPtr;
  lParam: IntPtr): IntPtr;
begin
end;

procedure RichTextBoxEx.InsertLink(text: string);
begin
  InsertLink(text, Self.SelectionStart);
end;

procedure RichTextBoxEx.InsertLink(text: string; position: Integer);
begin
  if ((position < 0) or (position > Self.Text.Length)) then
    raise ArgumentOutOfRangeException.Create('position');
  Self.SelectionStart := position;
  Self.SelectedText := text;
  Self.Select(position, text.Length);
  Self.SetSelectionLink(True);
  Self.Select((position + text.Length), 0);
end;

procedure RichTextBoxEx.InsertLink(text: string; hyperlink: string);
begin
  InsertLink(text, hyperlink, Self.SelectionStart);
end;

procedure RichTextBoxEx.InsertLink(text: string; hyperlink: string; position: Integer);
begin
  if ((position < 0) or (position > Self.Text.Length)) then
    raise ArgumentOutOfRangeException.Create('position');
  Self.SelectionStart := position;
  Self.SelectedRtf := (((('{\rtf1\ansi ' + text) + '\v #') + hyperlink) + '\v0}');
  Self.Select(position, ((text.Length + hyperlink.Length) + 1));
  Self.SetSelectionLink(True);
  Self.Select((((position + text.Length) + hyperlink.Length) + 1), 0);
end;

procedure RichTextBoxEx.SetSelectionLink(__link: Boolean);
begin
  SetSelectionStyle(CharFormat2Mask.Link, );
end;

function RichTextBoxEx.GetSelectionLink: Integer;
begin
  Result := GetSelectionStyle(CharFormat2Mask.Link, CharFormat2Effect.Link);
end;

procedure RichTextBoxEx.SetSelectionStyle(mask: CharFormat2Mask; effect: CharFormat2Effect);
var
  lpar: IntPtr;
  wpar: IntPtr;
  cf: CharFormat2;
begin
  cf := CharFormat2.Create;
  cf.cbSize := (Cardinal(Marshal.SizeOf(cf)));
  cf.dwMask := mask;
  cf.dwEffects := effect;
  wpar := IntPtr.Create(SCF_SELECTION);
  lpar := Marshal.AllocCoTaskMem(Marshal.SizeOf(cf));
  Marshal.StructureToPtr(cf, lpar, False);
  SendMessage(Self.Handle, Message.SetCharFormat, wpar, lpar);
  Marshal.FreeCoTaskMem(lpar);
end;

function RichTextBoxEx.GetSelectionStyle(mask: CharFormat2Mask; effect: CharFormat2Effect): Integer;
type
  TArrayOfArrayOfWideChar = array of array of WideChar;
var
  state: Integer;
  lpar: IntPtr;
  wpar: IntPtr;
  cf: CharFormat2;
begin
  cf := CharFormat2.Create;
  cf.cbSize := (Cardinal(Marshal.SizeOf(cf)));
  cf.szFaceName := New(TArrayOfArrayOfWideChar, 32);
  wpar := IntPtr.Create(SCF_SELECTION);
  lpar := Marshal.AllocCoTaskMem(Marshal.SizeOf(cf));
  Marshal.StructureToPtr(cf, lpar, False);
  SendMessage(Self.Handle, Message.GetCharFormat, wpar, lpar);
  cf := (CharFormat2(Marshal.PtrToStructure(lpar, TypeOf(CharFormat2))));
  
  if ((cf.dwMask and mask) = mask) then
    if ((cf.dwEffects and effect) = effect) then
      state := 1
    else
      state := 0
  else
    state := -1;
  Marshal.FreeCoTaskMem(lpar);
  Result := state;
end;

end.
(°¿°) MaBuSE - proud to be a DP member
(°¿°) MaBuSE - proud to be a "Rüsselmops" ;-)
  Mit Zitat antworten Zitat
Robert_G
(Gast)

n/a Beiträge
 
#9

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 14. Jul 2005, 20:50
Hi Mabuse ,
Zitat von MaBuSE:
Ich hoffe diese Info hilft Euch weiter
Ich brauche es ja nicht.
Außerdem glaube ich, dass der Reflector besser geeignet ist. Er ist auch einfach der coolste class browser für die FCL.
IMHO sogar so gut, dass ich den aus dem VS03 bzw. aus dem VS05 ohne mit der Wimper zu zucken dagegen ersetzen lassen würde.
Es gibt mittlerweile auch ein Addin, dass nicht nur einzelne Klasse sondern ganze Assemblies als komplettes Projekt in der Wahlsprache erzeugt. (Viel Spass an alle, die weder XenoCode noch den DotFuscator kennen )
  Mit Zitat antworten Zitat
Benutzerbild von Taladan
Taladan

Registriert seit: 5. Aug 2003
Ort: Osnabrück
505 Beiträge
 
Delphi 2005 Professional
 
#10

Re: Brauche hilfe bei übersetzung von C# in ObjectPascal (.N

  Alt 14. Jul 2005, 21:29
Was dieser Barbelcodegenerator nicht kennt, lässt er scheinbar aus ohne eine Bemerkung.
Leider stehen mir die Dinge wie das BDN nicht zur Verfügung. Ich nutze lediglich eine Personaledition

Delphi-Quellcode:
procedure RichTextBoxEx.SetSelectionLink(link: Boolean);
begin
  SetSelectionStyle(CFM_LINK, );
end;
Zitat von Robert_G:
spachreferenz von D.Net
Ich habe lediglich eine Onlinehilfe bei meiner Delphiversion. Wo sollte ich diese Referenz finden?

Zitat von Robert_G:
Du solltest aber flexibler im Umgang mit dem MSDN, der .Net OH und der spachreferenz von D.Net sein.
Wenn ich nicht weiß, nach was ich suchen soll, dann ist das wie die berümte Nadel im Heuhaufen. (Davon mal abgesehen, das die deutschen MSDN stark zu Wünschen übrig lässt und die Suchfunktion schlechter ist, als die OH von Delphi, die (bei mir zumindest) zu 90% nichts auf Anhieb findet.


Zitat von Robert_G:
Das sind Aufzählungstypen ähnlich zu denen aus Delphi32.
Meinst du damit Records oder Arrays?

Zitat von Robert_G:
zweitens sind Auzählungen type safe.
was soll das heißen? (Das Safe sicher heißt ist mir klar )
Marco
Wer Rechtschreibfehler findet, der darf sie behalten

Carpe Diem - Nutze den Tag (und zwar den ganzen!)
  Mit Zitat antworten Zitat
Antwort Antwort
Seite 1 von 2  1 2      


Forumregeln

Es ist dir nicht erlaubt, neue Themen zu verfassen.
Es ist dir nicht erlaubt, auf Beiträge zu antworten.
Es ist dir nicht erlaubt, Anhänge hochzuladen.
Es ist dir nicht erlaubt, deine Beiträge zu bearbeiten.

BB-Code ist an.
Smileys sind an.
[IMG] Code ist an.
HTML-Code ist aus.
Trackbacks are an
Pingbacks are an
Refbacks are aus

Gehe zu:

Impressum · AGB · Datenschutz · Nach oben
Alle Zeitangaben in WEZ +1. Es ist jetzt 14:37 Uhr.
Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz