Wednesday, December 14, 2011

Writing Hello World for WinRT in Delphi

There is relatively little information out there on developing Native Metro applications, especially for languages other than those that Microsoft has provided projections for (C++, C#, and JavaScript). Other languages, including Delphi, need to create their own projections before they can use them effectively. I've been investigating getting Delphi to produce native applications for WinRT. This is a rough low level look at the WinRT native APIs, and how to use them from a language that isn't C#, C++, or JavaScript. Eventually this investigation will lead to development of Delphi wrappers around the Windows 8 WinRT classes that will be much easier to use. Much of the discussion in this post is very similar to Ian Griffiths discussion on Real Native WinRT Development, but where he's using C++, I'm using Delphi. If you're interested in more technical detail about what's going on behind the scenes, I suggest you give that article a read.

I started with an empty console application, and removed the {$APPTYPE CONSOLE} directive. Essentially this just allows me to have a Windows application that doesn't use VCL. Eventually this application will need to be wrapped up as a AppX package, I'll discuss that more in depth later. It seems that WinRT XAML applications can be run outside of Metro, so for now I'm take advantage of that.

I'm going to jump around in the code a bit, sharing important as it comes up. Lets start with the uses clause:
program SampleWinrt;

  Winapi.Winrt in 'Winapi.Winrt.pas',
  AllWinRt in 'Generated\AllWinRt.pas',
  WinRtHelpers in 'WinRtHelpers.pas';
There are three new units here:

  • Winapi.Winrt contains translations of the new global WinRT APIs. These are essentially the functions and datatypes defined in the Windows Runtime C++ reference: things such as RoInitialize and WindowsCreateString, etc.
  • AllWinRt contains all the enumerations, records, and interfaces defined in the Windows Metadata files. This file was generated by a tool that turns the metadata into delphi style interfaces. I'll go into the details of more of this process at a later time.
  • WinRtHelpers contains some helper classes that reduce the amount of code one needs to write in order to use the native APIs. This is the starting of a Delphi wrapper around the API to make the code more "Delphi". Currently, it contains a TInspectableObject-- which similar to TInterfacedObject but also implements the IInspectable interface -- and TWindowsString -- a helper class to convert strings to/from HSTRINGs.
Next up, we need to initialize our application. So lets look at the main program body:
This code is just to initialize the Windows Runtime, and make sure it gets uninitialized on termination. RoInitialize is similar to COM's CoInitialize -- all threads that interact with WinRT objects must call RoInitialize prior to using it. The application can be initialized as single threaded or multithreaded. Ian Griffiths had difficulty getting the RO_INIT_SINGLETHREADED and likewise my app seems to have issues starting up as single threaded. I suspect this problem may just be a bug in the Metro API.

There are a couple of Application Runtime classes in the WinRT framework: Windows.ApplicationModel.Core.CoreApplication, and Windows.UI.Xaml.Application. The Xaml Application is easier to set up, so we'll start with that one. It is interesting to be able to create Xaml applications in Delphi, because immediately we can take advantage of all the Xaml controls provided by Microsoft as well as consume third party controls (regardless of implementation language) and even provide libraries of additional Xaml components that could be consumed by Delphi or other language projections.

procedure Main;
  Factory: IApplicationFactory;
  App: IApplication;
  insp, outer, inner: IInspectable;
  outer := TDerivedApp.Create;
  OleCheck(RoGetActivationFactory(TWindowsString('Windows.UI.Xaml.Application'), IApplicationFactory, insp));
  Factory := insp as IApplicationFactory;
  app := Factory.CreateInstance(outer as IApplicationOverrides, inner);
  TDerivedApp(outer).inner := inner as IApplicationOverrides;
  app := nil; // App needs to be _Released first, otherwise it AVs
Here we create a TDerivedApp (which I'll expand on below), request a Xaml ApplicationFactory, and construct a IApplication specifying the TDerivedApp is the outer implementation of IApplicationOverrides. The ApplicationFactory provides an Inner implementation, which we store off so that we can make inherited calls. Finally we Run the app. This is sort of a bizarre inheritance model provided by WinRT that I'll gloss over here. Ian Griffiths has an in depth article about how to create inherited WinRT classes, give that a read for some of the more technical details of how it's implemented in C++.

Everything here is being stored in Interfaces, so it's reference counted. Even our classes, such as TDerivedApp are reference counted. TDerivedApp derives from TInspectableObject, which derives from TInterfacedObject from System. The Delphi compiler automatically generates calls to _Release, making this code look a lot cleaner than the raw C++ version. Note however that App is being initialized to nil manually before exiting. If Inner is released first, WinRT crashes. I haven't investigated closely, but my suspicion is that Inner may actually be a weak reference to the same object as App, and releasing both is unnecessary/incorrect.

So what is our TDerived app? It's an object that implements Windows.UI.Xaml.IApplicationOverrides so we can actually define the behavior of our application.

  TDerivedApp = class(TInspectableObject, IApplicationOverrides)
    FInner: IApplicationOverrides;
    // IApplicationOverrides interface
    procedure OnInitialize; safecall;
    procedure OnActivated(args: IActivatedEventArgs); safecall;
    procedure OnLaunched(args: ILaunchActivatedEventArgs); safecall;
    procedure OnFileActivated(args: IFileActivatedEventArgs); safecall;
    procedure OnSearchActivated(args: ISearchActivatedEventArgs); safecall;
    procedure OnSharingTargetActivated(args: IShareTargetActivatedEventArgs); safecall;
    procedure OnFilePickerActivated(args: IFilePickerActivatedEventArgs); safecall;

    property inner: IApplicationOverrides read FInner write FInner;
Note, like in C++, we have to implement all the entries in the interface, even if we don't want to handle those events. Implementation of those methods will just be a pass through to the Inner IApplicationOverrides provided by the Activation Factory. For example:
procedure TDerivedApp.OnActivated(args: IActivatedEventArgs);
Eventually there should be class wrappers that handle all the inheritance for you if you don't want to override methods. When the Application Runs, we get an OnLaunched event. That's the one event we wanted to hook up, so let's do that:
procedure TDerivedApp.OnLaunched(args: ILaunchActivatedEventArgs);
  content = '<TextBlock xmlns="" ' +
            '  Name="Text" TextAlignment="Center" HorizontalAlignment="Center" ' +
            '  VerticalAlignment="Center" FontSize="56">' +
            '  <Run Text="Hello World"/>' +
            '  <LineBreak/>' +
            '  <Run Text="Delphi"/>' +
            '  <LineBreak/>' +
            '  <Run Text="Metro Native App (Xaml)"/>' +
  WinStatic: IWindowStatics;
  ReaderStatic: IXamlReaderStatics;
  // Get the IWindowStatics
  RoGetActivationFactory(TWindowsString(SWindow), IWindowStatics, WinStatic);
  // Get an IXamlReaderStatics
  RoGetActivationFactory(TWindowsString(SXamlReader), IXamlReaderStatics, ReaderStatic);
  // Populate Xaml
  WinStatic.Current.Content := ReaderStatic.Load(TWindowsString(content)) as IUIElement;
  // Activate the current view
  FInner.OnLaunched(args); // inherited call;
Here we just load some constant XML data into the current frame using an XamlReader. It would be easy to design your Xaml in a separate file using Rad Studio or your favorite XML editor and storing on disk it along side your Application, but for simplicity's sake I've just included it inline.

And that's what it takes to present some text in Metro Xaml controls. Obviously I've omitted some code here; I'll see if I can minimize the AllWinRT and Winapi.Winrt units to only the APIs used in this example to provide a full code sample.


  1. Are the WinRT (win8 rt units) you use in the sample available in the current package or somewhere on the web?

  2. No, they are not available. Because Windows 8 is still in Developer Preview and the APIs could possibly change, and because this represents only preliminary research on how the Delphi API will look, I hesitate to make my translations available.

    I would however like to provide enough of it to let people take a look at this example and run it for themselves; I hope to get that out soon.

  3. Thank you, Thom.

    It's a very interesting article. The million question: FireMonkey or XAML? Or where FireMonkey, and where XAML?

    Best regards. :)

    Al Gonzalez.

  4. Thom, have you been able to update to make it compatible with the consumer preview version ? keep up the great work! :-)

  5. It truly is imperative in order to try to remember that you should stay positive within your tone or approach while
    paper writing service your dissertation card-stock. Write in an appropriate tone so that the followers appreciate examining the dissertation proposal.

  6. Thanks for everything guys

  7. A person who has had experience of Visual Chief will remark the similaries of the Delphi and Visual Chief IDEs. Equally use 'Forms' that are the basis of the building blocks of Windows programs, excluding of course the underlying languages are different. sbobet,

  8. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.
    werkblad keramiek

  9. Thank you for posting this.You most absolutely have built this blog website into something special.
    dekton keukenwerkblad

  10. I really be grateful for your blog, you have completed the great job. Thanks for the bunch of excellent resourceful site.
    terrazzo keukenblad

  11. Thank you for your sharing! I really like to read it,So good to find somebody with some original thoughts on this subject .
    bra tape

  12. Another great post, I appreciate all the work you put into this site, helping out others with your fun and creative works.

  13. Thanks on your marvelous posting! I really enjoyed reading it, you’re a great author.Please visit here:
    Packers And Movers Hyderabad

  14. I loved this one. It has given me courage to try scarier things. I tend to steer clear of them but not anymore.Packers And Movers Jaipur

  15. Thanks on your marvelous posting! I really enjoyed reading it, you’re a great author.Please visit here:
    Packers And Movers Chennai

  16. Generally I don't read anything but thanks for writing when i read this i felt how graceful as a writer you are.thank you for posting-Packers and Movers Kolkata

  17. Thanks have been given the opportunity to comment. Hopefully what you provided is useful for all those who need them. Visit my website if you want to know more about:Situs Judi poker

  18. I like the post format as you create user engagement in the complete article. It seems round up of all published posts. Thanks for gauging the informative posts.
    cara menggugurkan kandungan
    cara menggugurkan kandungan

  19. This comment has been removed by the author.

  20. QuickBooks Tech Support Phone Number is one the best accounting assistance available which can be accessed through QuickBooks Helpline Number. We are able to resolve all your QuickBooks related issues through our Intuit certified QuickBooks Pro-Advisors.

  21. QuickBooks Payroll Support Phone Number. For any kind of queries or any other related issue, we encourage you to call us at QuickBooks Payroll Support Phone Number +1-888-396-0208.

  22. Best technical support by Intuit professionals for QuickBooks installation, updates, setup, migration, data recovery, company file repair and data services.
    QuickBooks Payroll Service Number CAll 1888-567-1159 VISIT

  23. That was a great read. I really like your writing style and how you explain certain things. I will be back to read more from you.We also provide Technical Support for QuickBooks Payroll , if you face any problem with your QuickBooks Payroll you can just click here QuickBooks Basic Payroll Support. Or dial 1888-567-1159.

  24. Are you stuck with any technical issues with the device, software, operating system or browsers that you are presently using? If yes, we understand that how frustrating this situation could turn to be, especially if you are trying to do some important work and couldn’t complete it due to the technical bugs. Dial QuickBooks Support Phone Number 1888-396-0208 , If you are facing Errors in your Quickbooks.

  25. QuickBooks 2018 Desktop version for Windows has been launched and it is full of exciting and innovative features and tools. Furthermore, enhancement to older version of the software is also made within the new release of QuickBooks Point Of Sale Support Phone Number 2018 upgrade.

  26. Move up to QuickBooks Tech 2018 now and experience the most recent highlights including multi-screen support, batch receipt preparing, enhanced inquiry choice, mobile receipt process and that's only the tip of the iceberg. Call Quickbook Tech Support Phone Number +1888-396-0208 whenever for QB Tech 2018 Setup, Installation and Updates. Pick your phone and dial our toll free number anytime, We are here to help you 24/7.

  27. The QuickBooks Support Phone Number 1888-396-0208 has numerous guaranteed professionals who are constantly prepared to give a moment arrangement regardless of the kind of issue you are confronting. The Quickbooks undertaking support has exceptionally prepared experts, who can deal with a wide range of issues one next to the other, in the meantime.

  28. Online Business Analytics, This is an add-on tool which opens up numerous more options for QuickBooks Enterprise clients. This device helps in opening information in QuickBooks Enterprise software in such a way you don't have to enter subtle elements like numbers and so forth to run reports of any sort. It is advised to take the help from QuickBooks Enterprise Support phone Number 1800-291-2485 and get your Tool Install.

  29. Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
    Webdesining course in chennai

  30. The Number itself says that it's the fundamental and right Tech advantage for your business. In case you need any help call our QuickBooks Customer service Phone Number -- to get minute support from our authorities.

  31. After some time QuickBooks has turned into a necessary piece of numerous little and medium-sized entrepreneurs to run and deal with their records. The software accompanies different accommodating highlights for their clients and one of them is the adjust director, however now and again there can be circumstances where a client of this bookkeeping software may need to uninstall Intuit QuickBooks Sync Manager. This article gives the means on the most proficient method to do call our QuickBooks Sync Manager

  32. The QuickBooks Runtime Error 429 happens generally because of the issues with ActiveX or .NETCOM DLL being opened yet not enlisted totally with your workstation. With the arrangement said beneath, you can without much of a stretch determination your How to Fix Quickbooks Runtime Error 429.

  33. Quickbooks Enterprise Phone Number 1888-557-6950. Quickbooks Enterprise Version of Intuit Quickbooks, This is extremely valuable apparatus for maintaining your business effectively. Yet, numerous time comes bunches of error , issue and issue that you as an Enterprise client confront more issue while utilizing this product.

  34. Manish Packers and Movers Pvt Ltd as a Services providing company can make all the difference to your Home Relocation experience. Indore based Company which offers versatile solutions, Right team that easily reduce the stress associated with a Household Shifting, Vehicle Transportation. we help things run smoothly and reduce breakages and offer you seamless, Affordable, Reliable Shifting Services, Compare Shifting Charges, Visit :
    Manish Packers and Movers Ptv Ltd @
    Packers and Movers Indore @
    Manish Packers Indore @
    Packers and Movers Gurgaon @
    Packers and Movers Kolkata @
    Packers and Movers Mumbai @
    Packers and Movers Bhopal @
    Packers and Movers Nagpur @
    Packers and Movers Raipur @
    Packers and Movers Ahmedabad @

  35. Hire Manish Packers and Movers Pvt Ltd in India for hassle-free Household Shifting, Office Relocation, Car Transportation, Loading Unloading, packing Unpacking at affordable Price Quotation. Top Rated Safe and Secure Service Providers who can help you with 24x7 and make sure a Untroubled Relocation Services at Cheapest/Lowest Rate. Visit More :-
    Manish Packers and Movers Pvt Ltd
    Packers and Movers Bangalore
    Packers and Movers Gurgaon
    Packers and Movers Indore
    Packers and Movers Kolkata
    Packers and Movers Mumbai
    Packers and Movers Nagpur
    Packers and Movers Ahmedabad
    Manish Packers in Indore
    Manish Packers and Movers Pvt Ltd Sitemap

  36. It is an efficient programming as it consequently adjust your information with the QuickBooks Desktop Software. The QuickBooks Point Of Sales help in dealing with your business and leading deals exchange however there are chances that a client may experience a few errors. A few clients have announced error like Quickbooks POS Error 100 confine the client from getting to the product.

  37. [CENTER][SIZE=5]شركات مكافحة حشرات بجدة احباب طيبة لمكافحة جميع انواع حشرات
    شركة مكافحة حشرات بجدة[/URL] تعمل جاهدة للحصول على جميع رغبات عملائها الكرام، ولهذا توفر إليكم أفضل وأهم الخدمات التي تساعد العميل في إبادة الحشرات عن طريق اتباع [URL="شركة-مكافحة-حشرات-بمكة/"]شركة مكافحة حشرات بمكة[/URL]للأساليب الحديثة والوسائل التي تساهم في التخلص من كافة أنواع الحشرات التي تسبب الأمراض والفزع الشديد لأهل المنزل، تحرص [URL="شركة-مكافحة-حشرات-ورش-مبيدات-بجدة/"]شركات مكافحة حشرات بجدة[/URL] على أن تقوم باستخدام أقوى المبيدات الحشرية التي تقضي على بق الفراش والنمل الأبيض والعته والصراصير وأنواع مختلفة من الحشرات الزاحفة والطائرة، كل هذا بجانب المرشات الحديثة التي تعتمد عليها في عملية إبادة الحشرات.
    [URL=""]مكافحة الصراصير بجدة[/URL]
    الصراصير واحدة من أنواع كبيرة من الحشرات التي تصيب الإنسان بكثير من الأمراض الخطيرة، ولذا يجب أن يتم التخلص منها فور ملاحظة وجودها ومن أفضل الوسائل التي يلجأ إليها العميل هو أن يستعين بشركتنا شركة مكافحة صراصير بجدة لأنها الشركة الوحيدة التي تعتمد على استخدام مبيدات حشرية خاصة جداً لإبادة الصراصير والتخلص منها نهائياً.
    [URL=""]ارخص شركة مكافحة الفئران جدة[/URL]
    من منا يقبل أن تظل الفئران داخل بيته فالجميع لا يقبل بهذا الشيء أن يحدث لأن الفئران من القوارض الذي يكون من الصعب السيطرة عليها بالطرق التقليدية، كما أنها سريعة الانتشار وتتسبب في إصابة الإنسان بكثير من الأمراض المعدية والخطيرة، لذا يكون من الأفضل الاستعانة بشركتنا شركة مكافحة الفئران بجدة، لأنها توفر العديد من الأساليب التي تساهم في إبادة الفئران بأفضل الطرق التي لا تؤذي ولا تؤثر على صحة الإنسان بأي شكل من الأشكال.
    [URL=""]شركةمكافحة الحمام بجدة[/URL]
    تقدم شركتنا لكل عملائها الكرام خدمة تركيب طار الحمام بجدة، وهذا يساعدهم في التخلص من وقف الحمام والطيور على الشرفات والنوافذ والمكيفات، فنحن نقدم لكم طارد الحمام الخاص بالمكيفات فهو يعمل على منع الطيور من الوقوف وليس قتلهم كما يعتقد الكثيرون، وهذا يساهم في التخلص من فضلات الطيور التي تعمل على وجود الحشرات المسببة للأمراض، فالشركة تقوم بصنع طارد الحمام عن طريق استخدام الأشواك المصنوعة من أفضل المواد والذي يتم تثبيتها على قاعدة من الألمونيوم، ويتم ذلك على أيدي عمال متخصصين ولديهم خبرة كبيرة في هذا المجال

  38. [URL=""]شركة مكافحة بق الفراش بجدة[/URL]
    بق الفراش من الحشرات التي تنتشر في الفراش وفي الملابس الصوفية، ويجب أن يتم التخلص منها على فور ملاحظة وجود ولهذا يجب أن يتم الاتصال بشركتنا شركة مكافحة بق الفراش بجدة لإبادة الحشرات عن طريق استخدام المبيدات الحشرية العالمية الأكثر أماناً على صحة المواطنين، فنحن نقوم برش المبيدات الحشرية في وجود الأطفال وأصحاب المنزل.
    [URL=""]شركات مكافحة النمل الابيض بجدة[/URL]
    تعتبر شركة مكافحة النمل الأبيض بجدة من الشركات التي تعتمد في عملها على فريق مميز من عمال رش الحشرات، فهم يقوموا باستخدام أحدث أنواع المرشات التي تساعد في توصيل المبيدات الحشرية لأدق الأماكن بالمنزل، أيضاً استخدامهم لأحدث الوسائل التي تساعدهم في السيطرة على الحشرات بكافة أنواعها سواء النمل الأبيض، بق الفراش والفئران وغيرها من الحشرات والقوارض.
    [URL=""]شركة رش مبيدات بجدة[/URL]
    تحتاج عملية رش المبيدات الحشرية إلى عمال متخصصين في إبادة الحشرات، ولديهم الخبرة الطويلة في هذا النوع من الأعمال الشاقة ، كما أن الشركة تحرص على استخدام أقوى المبيدات الحشرية الألمانية والأمريكية، والتي لا تؤثر بصورة سلبية على صحة الإنسان أو البيئة بوجه عام.
    [URL=""]شركة رش حشرات بجدة[/URL]
    يعتمد رش الحشرات على فريق متميز من العمال الخبرة والمتميزين والتي توفر إليهم الشركة أحدث الوسائل والمعدات التي تستخدم في إبادة الحشرات والتخلص منها إلى الأبد، فرش الحشرات يدوم مفعوله بالمنزل لمدة تصل إلى 10 أشهر وأكثر، كما أن الشركة توفر الإبادة الدورية للتأكد من عدو وجود الحشرات والقوارض.[/SIZE][/CENTER]

  39. Quickbooks Enterprise 24x7 Support Number has a team of well-qualified technicians who are all set to resolve any of your queries, with QuickBooks Enterprise. Through QuickBooks Enterprise Phone Number these technical experts remain in touch, while giving expert opinion, relating QuickBooks Enterprise. The Quickbooks Enterprise customer Support Phone Number 1888-557-6950 has been able to solve the problems of customers in quick time.

  40. Intuit concocted a far reaching retail answer for all business segments QuickBooks Point Of Sale. It is accessible for both work area and in addition online business. QuickBooks Point Of Sale accompanies special cases includes as in following stock, constant reports, and so forth. This easy to use programming is anything but difficult to manage yet under a few conditions client may run over a few Errors which may go about as an obstacle in their work. Quickbooks POS Error 175305 is essentially an investigate store trade error.

  41. Norton antivirus is probably the most broadly used antivirus software program method. Norton Antivirus is generally a design name with the entire Norton Antivirus corporation which can be additional info popular amid the read more shopper. It’s a number of abilities include virus defense, firewall, security from effected Net contents and e-mail filtering and remote administration systems. In the event you come across some faults dial Norton Antivirus Technical Support Number which allow you to unravel your inquiries. Visit Here:

  42. QuickBooks Customer Service Number supports organizations to elucidate their application crashes and errors of QuickBooks. Minor companies often got discouraged that how much tax they would like to expend or there are various challenges arrives of their way that how bookkeeping is performed flawlessly. The computer software comes along with just check here Quickbooks customer support phone number and provides end users which have a system wherever they can fix their dilemma. Take a rapidly respond to from authorities via QuickBooks Tech Support Phone Number anytime and from anyplace. Visit Here:

  43. Apple ordinarily presents the unmatched technological innovation and its products and solutions in The purchasers. They provide to assist enterprises for a specific length of time when it expires. You should see inside the apple Get in touch with apple customer service number with a variety that permits you fairly Maybe effectively one of the most Net-Web-World-wide-web-web site practical empowers distributors In the authentic marketing rate tag ranges. Adequately, Inside the event, you will be Web World-wide-web website looking for to trace down great and straight absent apple phone number customer service info you definitely Unquestionably know-how added successfully will need to think about the apple iphone customer service phone number which prospective customers 24x7. The Qualified will desirous to maintenance the variously specialized blunders in a quick timeframe. Visit Here:

  44. Packers and Movers Pune Provide High Quality ***Household Shifting, Home/Office Relocation, Insurance, Packing, Loading, ###Car Transportation Service Pune and High experiences, Top Rated, Safe and Reliable, Best and Secure Packers and Movers Pune Team List. Get ✔✔✔ Affordable Rate Charts and Compare Quotation and Save Money and Time .
    Packers And Movers Pune

  45. Great!it is really nice blog information.after a long time i have grow through such kind of ideas.
    thanks for share your thoughts with us.
    Java training institute in chennai
    Best JAVA Training institute in Chennai
    Java Training
    Hadoop Training in Chennai
    Selenium Training in Chennai

  46. Thinking to buy a laptop and don't want to give more than BEST WINDOWS LAPTOP UNDER RS 25000 worry not as there are opportunities open online. These laptops are able of most of your necessary tasks such as web browsing, e-mails, reports, social networking, spreadsheets, making presentations and viewing HD videos. You, though, may not be ready to play high-end videos games and do some different tasks requiring higher-processing power. Visit Here: