Use TRegistry class in Delphi

The Windows Registry is a powerful tool that can be used to store and retrieve application settings and data. In this blog post, we’ll explore how we can use the registry in Delphi programming to seed data, withdraw data when the program is started, and protect sensitive information from prying eyes.

Seeding data in the registry One of the most common uses of the registry is to store application settings that can be accessed across multiple sessions. For example, if you want to remember the last path that the user opened a file from, you can store this information in the registry. To do this in Delphi, you can use the TRegistry class from the Registry unit:

uses

Registry;

procedure SaveLastPath(const APath: string);

var

Reg: TRegistry;

begin

Reg := TRegistry.Create;

try

Reg.RootKey := HKEYCURRENTUSER;

if Reg.OpenKey(‘Software\MyApp’, True) then

begin

Reg.WriteString(‘LastPath’, APath);

Reg.CloseKey;

end;

finally

Reg.Free;

end;

end;

In this example, we create a new instance of TRegistry, set the RootKey to HKEYCURRENTUSER, and open the key ‘Software\MyApp’ (which will be created if it doesn’t already exist) with the OpenKey method. We then write the last path to the registry using the WriteString method and close the key with the CloseKey method.

Withdrawing data from the registry Once we’ve stored data in the registry, we can retrieve it when the program starts up. For example, if we want to set the initial directory for the open dialog to the last path that the user opened a file from, we can read this information from the registry. To do this in Delphi, we can use the same TRegistry class:

function GetLastPath: string;

var

Reg: TRegistry;

begin

Result := ”;

Reg := TRegistry.Create;

try

Reg.RootKey := HKEYCURRENTUSER;

if Reg.OpenKey(‘Software\MyApp’, False) then

begin

Result := Reg.ReadString(‘LastPath’);

Reg.CloseKey;

end;

finally

Reg.Free;

end;

end;

In this example, we create a new instance of TRegistry, set the RootKey to HKEYCURRENTUSER, and open the key ‘Software\MyApp’ (which should exist) with the OpenKey method. We then read the last path from the registry using the ReadString method and close the key with the CloseKey method.

Protecting sensitive information in the registry Sometimes, we may need to store sensitive information in the registry, such as passwords or API keys. To protect this information from prying eyes, we can encrypt it before writing it to the registry and decrypt it when reading it back. To do this in Delphi, we can use the TRegistry class along with the EncryptString and DecryptString functions from the SysUtils unit:

function Encrypt(const AValue: string): string;

begin

Result := EncryptString(AValue);

end;

function Decrypt(const AValue: string): string;

begin

Result := DecryptString(AValue);

end;

procedure SavePassword(const APassword: string);

var

Reg: TRegistry;

begin

Reg := TRegistry.Create;

try

Reg.RootKey := HKEYCURRENTUSER;

if Reg.OpenKey(‘Software\MyApp’, True) then

begin

Reg.WriteString(‘Password’, Encrypt(APassword));

Reg.CloseKey;

end;

finally

Reg.Free;

end;

end

In this example, we define two helper functions: Encrypt and Decrypt. EncryptString and DecryptString are built-in functions in Delphi that use the Windows Data Protection API (DPAPI) to encrypt and decrypt strings, respectively. We can then use these functions to encrypt the password before writing it to the registry and decrypt it when reading it back.

To read the encrypted password from the registry, we can modify the GetLastPath function to include the Decrypt function:

function GetPassword: string;

var

Reg: TRegistry;

begin

Result := ”;

Reg := TRegistry.Create;

try

Reg.RootKey := HKEYCURRENTUSER;

if Reg.OpenKey(‘Software\MyApp’, False) then

begin

Result := Decrypt(Reg.ReadString(‘Password’));

Reg.CloseKey;

end;

finally

Reg.Free;

end;

end;

In this example, we read the encrypted password from the registry using the ReadString method and pass it to the Decrypt function to get the original password.

In conclusion, the Windows Registry is a powerful tool that can be used to store and retrieve application settings and data in Delphi programming. By using the TRegistry class and some helper functions, we can easily seed data, withdraw data when the program is started, and protect sensitive information from prying eyes.

  1. Use constants or variables to store registry keys and values Instead of hardcoding registry keys and values in your code, it’s a good practice to use constants or variables to make it easier to change them later. For example:

const

MyAppRegistryKey = ‘Software\MyApp’;

LastPathValue = ‘LastPath’;

procedure SaveLastPath(const APath: string);

var

Reg: TRegistry;

begin

Reg := TRegistry.Create;

try

Reg.RootKey := HKEYCURRENTUSER;

if Reg.OpenKey(MyAppRegistryKey, True) then

begin

Reg.WriteString(LastPathValue, APath);

Reg.CloseKey;

end;

finally

Reg.Free;

end;

end;

In this example, we define two constants, MyAppRegistryKey and LastPathValue, to store the registry key and value names, respectively. This makes it easier to change these values in the future without having to update all instances of the hardcoded strings in your code.

  1. Use try-finally blocks to ensure registry keys are properly closed When working with the registry in Delphi, it’s important to properly close registry keys after you’re done using them to prevent memory leaks and other issues. To ensure that registry keys are always properly closed, you can use a try-finally block like this:

var

Reg: TRegistry;

begin

Reg := TRegistry.Create;

try

// Open registry key and do some operations

finally

Reg.Free;

end;

end;

In this example, we create a new instance of TRegistry, open the registry key, and perform some operations. The finally block ensures that the registry key is always closed, even if an exception is thrown.

  1. Consider using alternative data storage options for large or complex data While the Windows Registry can be a useful tool for storing small amounts of application data, it may not be the best choice for large or complex data structures. In these cases, you may want to consider using alternative data storage options such as a database, XML or JSON files, or even a custom binary file format.

By considering these suggestions, you can use the Windows Registry in Delphi programming effectively and efficiently to store and retrieve application settings and data.

Related Posts

156 thoughts on “Use TRegistry class in Delphi

  1. I really like reading a post that can make men and women think.
    Also, many thanks for allowing for me to comment!

    Here is my blog post; nordvpn coupons inspiresensation – tinylink.in,

  2. I delight in, lead to I found just what I was taking
    a look for. You’ve ended my 4 day lengthy hunt! God Bless
    you man. Have a great day. Bye

    Here is my web site :: nordvpn coupons inspiresensation (t.co)

  3. Someone necessarily lend a hand to make severely
    articles I might state. This is the very first time I frequented your web page
    and to this point? I surprised with the analysis you made to make this actual submit incredible.
    Fantastic task!

    my web page :: nordvpn coupons inspiresensation –
    come.ac,

  4. nordvpn promotion 350fairfax
    Unquestionably consider that that you said. Your favorite justification seemed to be on the net the simplest thing to take note of.
    I say to you, I definitely get irked while other folks think about worries that they plainly do not realize about.
    You managed to hit the nail upon the highest and outlined out the entire thing without having side effect
    , folks can take a signal. Will probably be back to get more.
    Thank you

  5. Simply wanna remark on few general things, The website design is perfect, the articles is really superb. “To the artist there is never anything ugly in nature.” by Franois Auguste Ren Rodin.

  6. F*ckin’ remarkable things here. I’m very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a mail?

  7. Anticipate to attend some time to get right into a recreation,
    as the waitlists at Bellagio are a number of the longest in the metropolis.

    Tournament gamers should look elsewhere for motion, however the Bellagio presents a top-notch number of games for cash recreation gamers.
    All 37 of these tables are presently devoted to money recreation play at all
    times. That truth may deter players on the lookout for multi-table tournament action.
    The traditional bonus of 200 free spins on first deposit, however, seems quite modest.
    And especially with the high roller slots, players are
    additionally granted a relatively high stake. A good high roller
    casino what is considered A high roller characterized,
    amongst different things, by particular VIP tables with very high limits.
    There are massive variations when it comes to
    the attainable bets in on-line slots. Players also wants to take note of which video games qualify for use of the Excessive Curler Bonus and Free Spins.

    Casinos try intensely to draw these elite gamblers in order that they create increasingly luxury perks and facilities.
    When high rollers achieve profitable substantial prizes it leads to substantial financial adjustments in casino
    profits. Casinos try to deal with financial exposure by providing promotions which drive players to stay while preserving
    their fiscal stability. Excessive rollers adopt the informal name “whales” whereas supporting the worldwide
    evolution of the on line casino sector. The luxurious betting activities of elite
    gambling patrons convey substantial revenues to casinos because
    they place seven-digit stakes in particular person playing
    periods.
    Maintain studying, and I’ll show you tips on how to score free drinks in any
    Las Vegas casino and hold them coming. I’ll also share how and where to search out
    reduced-priced drinks on or close to the Las
    Vegas Strip. “Las Vegas rules” used to discuss with games that were typical of Downtown Las Vegas – double down allowed, dealer hits soft-17,
    resplits, and permitted insurance. Las Vegas guidelines also implied that re-splitting of aces and double after splitting were not allowed.
    Mandalay Bay has become considered one of Vegas’ premier destinations with its
    in depth amenities, upscale lodging, and status for excellent service.
    The advanced encompasses the primary resort tower and
    the Delano and 4 Seasons motels within Mandalay Bay, bringing the total room depend to over four,seven hundred.

    At any hour, you will see people crowding vibrant gaming flooring
    trying their luck. Massive wins and losses elicit intense reactions – emotional highs and lows including to the electric ambiance.
    Showgirls, magicians, acrobats, and musicians provide extra spectacle.
    The resort is especially famous for its affordability, making it a gorgeous
    option for those looking for a budget-friendly Las Vegas expertise.

    From its vigorous casino flooring and free gaming lessons to its family-friendly points of
    interest, Excalibur provides a novel, engaging, and accessible Las Vegas expertise.
    With neon lights flashing 24/7, Las Vegas units the stage for large wins, late nights, and nonstop revelry.
    For blackjack lovers, the city teems with possibilities – lavish Las Vegas resorts and casinos filled with
    tables working all hours and event action for those seeking critical play.

    When it involves high roller casinos, participant protection and safety of buyer information is paramount.
    Excessive roller players need assurance that their knowledge and private information shall be saved safe when taking part in in on-line casinos.

    That’s why many on-line casinos have taken intensive measures to guard the
    safety of cash transactions and participant particulars.

    Traveling at one foot per second, the slow-moving wheel makes one revolution in 30 minutes.
    It would not cease for riders to load or unload, so that they have to hop on and off its climate-controlled, 40-passenger cabins.
    Though the wheel seems very promising, its location means that
    the views will not be quite as spectacular as you would count on.
    Furthermore, the high price tag makes the helicopter journey
    look like a greater deal. Their RV resort has one hundred totally paved websites, spacious pull-throughs and first-class facilities, including a heated pool, sizzling tub and
    newly reworked restrooms. If you intend on exploring Reno Tahoe
    along with your RV or journey van, Grand Sierra Resort presents space so that
    you simply can park close by and play to your heart’s content material.
    Locals and guests rave about the huge William Hill Sports Book, where you
    can catch video games on a jaw-dropping 45-foot LED
    display.
    Circus Circus Resort & On Line Casino, a vibrant and family-friendly
    destination, is a unique blend of on line casino excitement and amusement park thrills positioned on the
    Las Vegas Strip. Opened in 1968, this iconic establishment presents a novel
    mix of gaming, leisure, and lodging choices. Step proper up and witness the magic of the Big Prime at Circus Circus.
    This iconic lodge and casino offers free circus acts throughout the day,
    that includes acrobats, jugglers, and clowns. It’s an efficient way to entertain the entire household with out
    breaking the financial institution. Dave & Buster’s is a national
    chain of arcades with all kinds of games, including coin pushers.
    They have a quantity of places in Las Vegas,
    including one at 3500 S Las Vegas Blvd, Las Vegas, NV 89109.

    In the glamorous world of gambling, high rollers are the elite
    players who wager large quantities of cash and enjoy the most interesting perks
    a on line casino can offer. Being a excessive
    curler works by partaking within the highest-level playing activities throughout the casino.
    As a excessive roller, you would possibly be typically entitled
    to unique perks, higher odds, and a better level of service.

    Examples of comps embrace no-cost jet transfers, limousine use, or different free stuff.
    That can be free hotel rooms, tickets to Las Vegas exhibits, or holidays elsewhere on the planet.
    Comps embrace meals and merchandise, or anything else a on line casino thinks
    gamers will like.

  8. So is seeing any on-line casino web site listed right here on NJ.com, as
    we solely review legal and regulated online casinos.

    PokerStars Casino is the global online poker giant’s entry into the net
    casino sphere. It contains a choice of prime quality games
    and has grown from a easy perk for on-line poker players into a standalone online casino with promos and
    provides just for online on line casino players. Like all online casinos,
    FanDuel On Line Casino has loads of slot video games so that you can play.

    PayPal is an easy method to make deposits at online playing websites and sportsbooks that accept real
    cash wagers. You can sign up for PayPal fairly shortly, which is compatible with most banks.

    PayPal is a more secure technique of cost than offering your bank
    card data to someone who could be extra tech-savvy. Earlier Than requesting a withdrawal from
    PayPal casino sites, you have to deposit actual cash and play cash-based betting games.

    If you wager using bonus funds, most casinos will demand you to meet a rollover requirement, which varies from casino to
    casino. The incontrovertible fact that they supply the choice
    to make funds using PayPal demonstrates that they know
    the significance of protecting one’s privateness on-line and the results of security breaches.

    As well, PayPal transactions are among the quickest to be processed by on-line casinos.
    PayPal additionally presents an additional layer of safety and anonymity, because you won’t be giving your private banking particulars
    to the web casino, only entry to your PayPal account. First, it could be very important
    find a casino that truly helps this methodology – not
    all do, so that is the biggest hurdle. If you reside in a country
    the place gambling is unlawful or unregulated, you might
    not be capable of use it to move money to and from casinos.

    Once approved, funds often arrive in your PayPal account inside minutes.
    There isn’t any need to re-enter card or bank particulars, and you can transfer
    it to your linked account or spend it from PayPal as you
    favor. One advantage of PayPal is that it keeps your monetary information private.
    It additionally works properly on cellular, making it a practical choice for players who need fast entry without dealing with card rejections or longer bank delays.
    There are never any charges assessed to you when you make PayPal deposits or withdrawals at BetRivers.
    There’s a $10 minimum to complete a deposit transaction, but no maximum restrict.
    BetRivers typically handles withdrawals using PayPal within two hours.

    The website is absolutely optimized for mobile play, together with a dedicated iOS and Android app.
    Deposits and withdrawals start at $10, with withdrawals typically processed inside two business days.
    QueenVegas elevates your gaming expertise with seamless PayPal
    transactions. Take Pleasure In fast, secure deposits and withdrawals while exploring an intensive selection of video games.
    Benefit from PayPal’s trusted popularity and unparalleled
    comfort. Captain Cooks On Line Casino ensures seamless transactions with PayPal,
    offering players a secure and handy cost technique. Take Pleasure In quick deposits and withdrawals, backed by PayPal’s robust security measures.

    Some casinos exclude e-wallets like PayPal from triggering
    welcome bonuses. If PayPal is excluded, you could want to use a
    debit card or ACH instead. If your transaction remains to
    be blocked, check your PayPal account for restrictions or verification holds.

    Utilizing your most well-liked system – mobile or pill – you can access the
    casino of your alternative proper from the embedded browser.

    You don’t even have to make use of a dedicate app, as there is not any want for it!

    Accessing your favourite casino could have you enjoying any kind of slots, card, desk or live games very quickly and can even allow you to make PayPal deposits in a fast and protected manner.
    The exceptionally user-friendly and simple design of PayPal’s fee system permits players to learn from fast casino sign-ups with PayPal.

    Emily “VegasMuse” Thompson is a seasoned on-line on line casino enthusiast from
    down beneath. With a eager eye for particulars and an inherent knack for strategizing, she has turned her passion for the online casino world right into a
    profitable writing career. Make your first deposit with PayPal utilizing the same
    e mail address for each your on line casino and PayPal accounts, and click the PayPal icon in the cashier.

    Follow the prompts to complete the transaction, and your PayPal deposit will be obtainable instantly.
    You can deposit and withdraw from $10 to tens of 1000’s of dollars
    with PayPal, making it versatile. PayPal’s
    constant monitoring system creates a safe buffer between your
    financial information and the casino platform.
    Approval time depends on their help hours and your verification standing as properly.
    Earlier Than your first withdrawal, you may be required to
    confirm your identity. It looks like PayPal has been around since the
    dawn of time, nevertheless it truly launched in 1998. Hundreds Of Thousands of
    users nonetheless have energetic accounts whereas others have
    ditched them for a better option. Preserving up with all the modifications can seem fairly challenging, however it’s par
    for the course.
    Fanatics On Line Casino provides a large choice of games, engaging bonuses, and safe fee options including PayPal.
    It companions with professional sports groups to provide unique promotions.
    Players can get pleasure from traditional on line casino med paypal games like slots, blackjack, roulette, poker, and stay vendor options.

  9. If you are going for finest contents like I do, only pay a visit this web
    site daily for the reason that it gives feature contents,
    thanks

  10. Hey! This is my 1st comment here so I just wanted to give a quick shout out and say I really enjoy reading your articles.
    Can you recommend any other blogs/websites/forums that deal with the same subjects?
    Thank you!

  11. Hello there I am so happy I found your web site, I really
    found you by error, while I was looking on Aol for
    something else, Regardless I am here now and would just like to say thanks a lot for a tremendous post
    and a all round enjoyable blog (I also love the theme/design), I don’t
    have time to read through it all at the moment but I have
    bookmarked it and also added your RSS feeds, so when I
    have time I will be back to read more, Please do keep up the fantastic
    job.

  12. obviously like your web site but you have to test the spelling on several
    of your posts. Several of them are rife with spelling issues and I to find it very troublesome to inform the truth then again I’ll certainly come back
    again.

  13. I all the time emailed this web site post page to all my associates,
    as if like to read it then my contacts will too.

  14. Good day! I know this is somewhat off topic but I was wondering if you knew where
    I could find a captcha plugin for my comment form?

    I’m using the same blog platform as yours and I’m
    having difficulty finding one? Thanks a lot!

  15. I’ve read some good stuff here. Definitely price bookmarking for revisiting.
    I wonder how much effort you place to create this type
    of excellent informative web site.

  16. I know this if off topic but I’m looking into starting my own blog and was wondering what all is needed to get setup?
    I’m assuming having a blog like yours would cost a pretty penny?

    I’m not very internet savvy so I’m not 100% positive.
    Any suggestions or advice would be greatly appreciated.
    Many thanks

  17. Hi! I’ve been reading your web site for a while now and finally got the bravery to
    go ahead and give you a shout out from Humble Texas!
    Just wanted to say keep up the great work!

  18. Nice blog! Is your theme custom made or did you download it from
    somewhere? A theme like yours with a few simple tweeks would really
    make my blog stand out. Please let me know where you got
    your theme. Bless you

  19. I simply couldn’t go away your website prior to suggesting that I extremely loved the usual information an individual provide in your guests?
    Is going to be back regularly to check up on new posts

  20. Spot on with this write-up, I seriously believe that
    this web site needs a great deal more attention. I’ll probably be returning
    to read more, thanks for the information!

  21. What’s Going down i’m new to this, I stumbled upon this I’ve discovered It absolutely useful and it has helped me out loads. I hope to contribute & assist different users like its aided me. Good job.

  22. Hello, i think that i saw you visited my blog thus i got here
    to return the prefer?.I’m attempting to find issues to improve my
    website!I guess its good enough to make use of a few
    of your ideas!!

Leave a Reply

Your email address will not be published. Required fields are marked *