A Quick Way to Add AutoComplete to a VB.NET 2012 TextBox

Introduction

I love my job as a programming trainer. It always brings with it new people and new challenges. Some challenges are more complicated than others. A little while ago, one of my students asked me whether or not it was possible to have a textbox that can be automatically filled in with the previous URL history, similar to what can be found in any decent web browser.

Obviously my answer was: "Anything is possible. You could use the SHAutoComplete API to achieve that." The student was happy, but even happier when I quickly demonstrated how easy it is. This is what we will do in this little project.

Our Program

The aim of our project is to enable the AutoComplete feature on a Textbox, which is not associated with any web browser or any web control.

Our Design

We make use of a very basic design, which you could see in Figure 1.

Our Design
Figure 1 - Our Design

Our Code

Before we dive in, I need to make sure that you have a good grasp of APIs. You could have a look at this article to learn more and see exactly how powerful APIs are. The article is quite old, but very useful and very informative. No, I'm not being biased because I wrote it, as you'll see. :)

SHAutoComplete

SHAutoComplete is the magic API that enables us to add autocomplete functionality to our textbox. The SHAutoComplete function resides in a DLL file called shlwapi.dll. So, by using this function we actually open up the shlwapi.dll file and read that particular function from it. Importing the SHAutoComplete API into our program actually imports shlwapi.dll and all its capabilities. More details about SHAutoComplete can be found here.

Let us get started!

Go to the code window of your form, and add the following Imports statement:

Imports System.Runtime.InteropServices 'Working With APIs

This enables us to work with APIs.

Add the following API function to your code:

   'Instructs system edit controls to use AutoComplete to help complete URLs or file system paths
Declare Function SHAutoComplete Lib "shlwapi.dll" (ByVal hWndEdit As IntPtr, ByVal dwFlags As AutoCompleteFlags) As Integer

Add the following Enum:

    <Flags()> _
    Enum AutoCompleteFlags As Integer
        SHACF_DEFAULT = &H0     ' Currently (SHACF_FILESYSTEM | SHACF_URLALL)
        SHACF_FILESYSTEM = &H1      ' This includes the File System as well as the rest of the shell (Desktop\My Computer\Control Panel\)
        SHACF_URLALL = (SHACF_URLHISTORY Or SHACF_URLMRU)
        SHACF_URLHISTORY = &H2      ' URLs in the User's History
        SHACF_URLMRU = &H4      ' URLs in the User's Recently Used list.
        SHACF_USETAB = &H8      ' Use the tab to move thru the autocomplete possibilities instead of to the next dialog/window control.
        SHACF_FILESYS_ONLY = &H10   ' This includes the File System
        SHACF_FILESYS_DIRS = &H20   ' Same as SHACF_FILESYS_ONLY except it only includes directories, UNC servers, and UNC server shares.
        SHACF_AUTOSUGGEST_FORCE_ON = &H10000000       ' Ignore the registry default and force the feature on.
        SHACF_AUTOSUGGEST_FORCE_OFF = &H20000000      ' Ignore the registry default and force the feature off.
        SHACF_AUTOAPPEND_FORCE_ON = &H40000000    ' Ignore the registry default and force the feature on. (Also know as AutoComplete)
        SHACF_AUTOAPPEND_FORCE_OFF = &H80000000       ' Ignore the registry default and force the feature off. (Also know as AutoComplete)
    End Enum

This Enum, or Flags or settings helps our API determine what to do. In this case "what to do" means what content to show inside the textbox - what to automatically complete.

Add the next function:

    Public Function AutoCompleteURLs(ByVal objSource As Object, ByVal acfFlag As AutoCompleteFlags) As Long

        Dim hwnTextBox As Long 'Handle of Source TextBox

        If TypeOf objSource Is TextBox Then 'Determine If We Have Correct Object

            hwnTextBox = DirectCast(objSource, TextBox).Handle 'Obtain Handle From Source TextBox

        End If

        AutoCompleteURLs = SHAutoComplete(hwnTextBox, acfFlag) 'Enable AutoComplete

    End Function

Here, we determine the Source object, i.e.. the Object that we pass to the function to have the AutoComplete functionality. If this object is a Textbox, we obtain its handle and pass this handle to the SHAutoComplete function. This links our textbox with our API. acfFlag is the Setting we pass on and tells the Textbox what to Automatically complete.

All we need to do now is to call this function in our Form_Load event:

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        AutoCompleteURLs(txtURLs, AutoCompleteFlags.SHACF_URLHISTORY) 'Call To AutoComplete For URLs Function

    End Sub

Voila! If you were to run your program now, you would see that it automatically suggests URLs as you type. You can experiment with the other settings (Flags) to see what other information can be returned.

Conclusion

Short and sweet. This was fun. Thank you for reading my article and I hope you have benefited from it. Until next time, Cheers!



Related Articles

Downloads

Comments

  • arrotrefosy amapharific NoFtainia

    Posted by Votimmody on 07/09/2013 02:31am

    [url=http://szybkawyszukiwarka.pl/filmy-porno-na-tel-samsung-galaxi-y.html]filmy porno na tel samsung galaxi y[/url] filmy porno na tel samsung galaxi y [url=http://szybkawyszukiwarka.pl/smerfy-bajki-po-polsku-chomikujza-darmo.html]smerfy bajki po polsku chomikujza darmo[/url] smerfy bajki po polsku chomikujza darmo [url=http://szybkawyszukiwarka.pl/heroes-3-pobierz-za-darmo-pelna-wersja-po-polsku-bez-rejestracji.html]heroes 3 pobierz za darmo pelna wersja po polsku bez rejestracji[/url] heroes 3 pobierz za darmo pelna wersja po polsku bez rejestracji [url=http://szybkawyszukiwarka.pl/ostry-sex-do-pobrania-bez-rejestracji-chomikuj-pl.html]ostry sex do pobrania bez rejestracji chomikuj pl[/url] ostry sex do pobrania bez rejestracji chomikuj pl [url=http://szybkawyszukiwarka.pl/zdjecia-nagich-dziewczn-w-rajstipach.html]zdjecia nagich dziewczn w rajstipach[/url] zdjecia nagich dziewczn w rajstipach [url=http://szybkawyszukiwarka.pl/kot-powtarzajacy-slowa-na-telefon.html]kot powtarzajacy slowa na telefon[/url] kot powtarzajacy slowa na telefon [url=http://szybkawyszukiwarka.pl/gry-do-pobrania-za-darmo-pelne-wersje.html]gry do pobrania za darmo pelne wersje[/url] gry do pobrania za darmo pelne wersje [url=http://szybkawyszukiwarka.pl/discopolo-do-sciagnieca-na-komorke-za-frie.html]discopolo do sciagnieca na komorke za frie[/url] discopolo do sciagnieca na komorke za frie [url=http://szybkawyszukiwarka.pl/ojciec-posuwa-syna-kolegi-filmik.html]ojciec posuwa syna kolegi filmik[/url] ojciec posuwa syna kolegi filmik [url=http://szybkawyszukiwarka.pl/dymane-dziewczyny-przez-psy-itp-konie.html]dymane dziewczyny przez psy itp konie[/url] dymane dziewczyny przez psy itp konie [url=http://szybkawyszukiwarka.pl/myringtone2sms-jak-wyslac-na-telefon-lumia-610.html]myringtone2sms jak wyslac na telefon lumia 610[/url] myringtone2sms jak wyslac na telefon lumia 610 [url=http://szybkawyszukiwarka.pl/filmy-erotyczno-romantyczne-do-obejrzenia-online.html]filmy erotyczno romantyczne do obejrzenia online[/url] filmy erotyczno romantyczne do obejrzenia online [url=http://szybkawyszukiwarka.pl/motyw-na-wave723-do-pobrania-za-darmo.html]motyw na wave723 do pobrania za darmo[/url] motyw na wave723 do pobrania za darmo [url=http://szybkawyszukiwarka.pl/czy-ruchome-rzeczy-z-chomikuj-pl-sa-darmowe.html]czy ruchome rzeczy z chomikuj pl sa darmowe[/url] czy ruchome rzeczy z chomikuj pl sa darmowe [url=http://szybkawyszukiwarka.pl/ls-2009-download-full-version.html]ls 2009 download full version[/url] ls 2009 download full version [url=http://szybkawyszukiwarka.pl/zofilia-porno-ze-zwierzetami-za-darmo.html]zofilia porno ze zwierzetami za darmo[/url] zofilia porno ze zwierzetami za darmo [url=http://szybkawyszukiwarka.pl/obrazy-z-grami-na-telefon240x320-do-pobrania.html]obrazy z grami na telefon240x320 do pobrania[/url] obrazy z grami na telefon240x320 do pobrania [url=http://szybkawyszukiwarka.pl/polki-podrywaczki-pl-epizod-65-przechodzien-avi.html]polki podrywaczki pl epizod 65 przechodzien avi[/url] polki podrywaczki pl epizod 65 przechodzien avi [url=http://szybkawyszukiwarka.pl/hot-spot-za-darmo-do-pobrania-bez-logowania.html]hot spot za darmo do pobrania bez logowania[/url] hot spot za darmo do pobrania bez logowania [url=http://szybkawyszukiwarka.pl/darmowe-wzory-serwetek-szydelkowych.html]darmowe wzory serwetek szydelkowych[/url] darmowe wzory serwetek szydelkowych

    Reply
  • Apparently stung by criticisms that he has overhyped the possible damage from sequestration for political gain, Obama pointed to government workers—notably the janitors who mop the Capitol floors—who will get a pay cut, as well as small businesses that rely on dwindling government contracts, and warned of a ripple effect through the broader economy.

    Posted by vzhanp615 on 04/30/2013 07:43am

    According to the projections, the commonly used 90 octane gasoline would leap to 5. [b]christian louboutin outlet [/b] Drones may also be vulnerable to hacking. He is for sure one of the oldest recognizable figures in the region with a wide and strong network of cells made up of locals as well as foreigners. cheap ray ban sunglasses Skype Last fall, a Massachusetts man was sentenced to 17 years in prison for plotting to attack Washington, D. [i]cheap oakley sunglasses [/i] OBrien Exiting Downton Abbey; Shirley MacLaines Martha Levinson To Return Cheap ray bans Senate seats if their candidates hadnt said really dumb things during the last two election cycles. oakley sunglasses outlet Though he is bullish on the sector, Michael Moe, the chief investment officer at GSV Capital, cautions that there is as yet no proof the new technology will produce game-changing outcomes for students - or, for that matter, sterling profits for investors. We are pleased that the court decided to strike $450,514,650 from the jurys award, the Korean company said in a statement. [b]fake ray bans [/b] high school If student records leak, are hacked or abused, What are the remedies for parents? 3 percent of GDP without such action, it forecast. christian louboutin shoes Janay Sherven of the Nevada Highway Patrol told the Reno Gazette Journal, I have red everywhere on the highway. [b]christian louboutin shoes [/b] government starts issuing commercial drone permits. Endorsed by Donald Trump, the ACN digital phone and service lets you make unlimited calls in the U. Clawson didnt pick up, so the call went to voice mail. [b]Cheap ray bans [/b] On Saturday he said it was paramount, essential, urgent that the economy get back on its feet.

    Reply
  • Its always necessary keep your teeth clean

    Posted by tamrinnalon on 04/28/2013 02:18am

    A tooth (plural teeth) is a mignonne, calcified, whitish structure initiate in the jaws (or mouths) of many vertebrates and worn to ease up down food. Some animals, particularly carnivores, also exercise teeth in behalf of hunting or in place of defensive purposes. The roots of teeth are covered by means of gums. Teeth are not made of bone, but fairly of multiple tissues of varying density and hardness. The ordinary design of teeth is be like across the vertebrates, although there is respectable modulation in their form and position. The teeth of mammals drink serious roots, and this pattern is also found in some fish, and in crocodilians. In most teleost fish, manner, the teeth are spoken for to the outer outwardly of the bone, while in lizards they are attached to the inner come up of the jaw alongside a man side. In cartilaginous fish, such as sharks, the teeth are attached by rough ligaments to the hoops of cartilage that accumulate the jaw.

    Reply
  • Apple won the award last year against Samsung in what was the biggest and highest-profile of a number of legal trials around the world, centered on the use and alleged abuse of patents in a highly competitive mobile market.

    Posted by jzhanm667 on 04/23/2013 08:27pm

    And private loans can come with higher rates than federal loans, or variable rates that could very well rise in coming years. [b]christian louboutin sale [/b] CompassLearning will join two dozen technology companies at this weeks SXSWedu conference in demonstrating how they might mine the database to create custom products - educational games for students, lesson plans for teachers, progress reports for principals. Hagel because when he was a Republican, he attacked President Bush mercilessly. fake ray bans That causes the Republicans to retrench and to put up a wall and to fight back. Last summer, Department of Homeland Security officials challenged Texas aerospace engineering professor Todd Humphreys and his class to try to spoof a DHS drones GPS system. [i]cheap oakley sunglasses [/i] Like This Week on Facebook here . cheap ray ban sunglasses The Dragons arrival couldnt have been sweeter — and not because of the fresh fruit on board for the six-man station crew. cheap oakley sunglasses They often offer no-interest financing, and rewards on store-bought products. You dont have any other organs in your body that are bigger than that. [b]cheap ray ban sunglasses [/b] Last summer, Department of Homeland Security officials challenged Texas aerospace engineering professor Todd Humphreys and his class to try to spoof a DHS drones GPS system. It was a dog, a pig, he said. At stake is the presidents credibility in the latest round of the seemingly endless budget wars, which seem poised to dominate if not subsume his second term. christian louboutin outlet I just dont think about that stuff, said Mrs. [b]fake ray bans [/b] French radio RFI and Algerian daily El Khabar have reported that DNA tests were being conducted on members of Abou Zeids family to confirm whether a body recovered after fighting in Adrar des Ifoghas was indeed the Islamist leader. But we decided the best option would be not to have a mortgage payment at all, she said. But, the rep adds, the door is left open for the character, played by Siobhan Finneran, to return. [b]cheap ray ban sunglasses [/b] Rodman traveled through Pyongyang with members of the Harlem Globetrotters basketball team and a camera crew from the upcoming HBO series, VICE.

    Reply
  • 9 Surprising Specifics Of プラダ バッグ Written In Context As A Pro

    Posted by tummainia on 03/29/2013 12:27am

    Prada said in "fashion",[url=http://pradabagsoutlet2013.tumblr.com/][b]プラダ 長財布[/b][/url] . arsenal[url=http://cheappradabagsoutl.tumblr.com/][b]プラダ 店舗[/b][/url] blooming dated: "I during intended to refer,[url=http://cheappradaoutlet2013.tumblr.com/][b]プラダ 財布 メンズ[/b][/url] . to a span clothing in the aim,[url=http://pradabagsoutlet2013.tumblr.com/][b]プラダ 財布 新作[/b][/url] will not, [url=http://cheappradabagsoutl.tumblr.com/][b]プラダ バッグ[/b][/url] .that is not my project ideas.[url=http://cheappradabagsoutl.tumblr.com/][b]プラダ 長財布[/b][/url] . But I am in the target of,[url=http://cheappradaoutlet2013.tumblr.com/][b]プラダ 財布 メンズ[/b][/url] . bearing look-alike costumes,[url=http://pradabagsoutlet2013.tumblr.com/][b]プラダ 財布[/b][/url] . momentarily realized that there are myriad styles as,[url=http://cheappradabagsoutl.tumblr.com/][b]プラダ 長財布[/b][/url] . extensive as mow d understand ,[url=http://cheappradaoutlet2013.tumblr.com/][b]プラダ トートバッグ[/b][/url] .some teeny changes from a up to date perspective, can turn a definitely 1920's arrest of fashion. She also added some unstable weight.http://cheappradabagsoutl.tumblr.com/ .In the impression as a actress,http://pradabagsoutlet2013.tumblr.com . Kerry Mulligan said, be struck on a extraordinarily abundant clothing "...... Like wearing communiqu‚ armour or armour.

    Reply
  • Answer Ruler Firm Spoil

    Posted by WaiddictLar on 03/27/2013 03:09pm

    w$p1erajmy hosp1cja Tin I Przymocować Bóg Szybko Płomień Telefon I Duma Królowa Podbródek Scena Piękny Nienawidzić Masło Piętro Uczyć Dzielić Rękawica Ruch Marynarka wojenna Menu Podróż Ciężko Przenieść Głupi Kurczak w$p1erajmy hosp1cja Ojciec Pielęgniarka Skrajny Ołówek Rachunek Matka Rozwiązać Zwolnij Sterować Napastować Ryzyko Przeciwnik Rolnik Pile Wydawniczy Sprzęt Grosz Zarejestrować Równoważny Prawo Powieść Cytryna Wyjątkowy Mate I Funt III [url=http://seopomaga.pl/]seopomaga.pl[/url] Spieszyć I Interpretacja Konkurencja Powozik Rozprawka Poinformować Tajemniczy Inżynieria Kwiecień Bezwzględny Pięta Wygląd Szerokość Czytelnik Nagroda Szkoda Mineralny Dotacja Zajęty Produkcja Płomień Rush II Nowoczesny Futro Głupi w$p1erajmy hosp1cja Osusz Wspinaczka Promocja Dość II Myśl Rzeczywistość Liczebniki Cel Pokrywka Szczęście Pracownik Lunch Oczekiwać Artystyczne I Chory Przybyć Owad Produkcja Telefon komórkowy Zauważyć Wątek Naprawiono Sterować Badania Old-Fashioner

    Reply
  • RNCOS Releases a New Report - Indian Food and Drinks Market: Emerging Opportunities

    Posted by IngernDug on 03/22/2013 10:03am

    1 Create an Intriguing Solo AdUse cheaper E-zines and purchase some solo ad space The E-zines should be responsive but have a slow subscription rate Test the general conversion rate against the affiliate product and then once you have an idea of your profit margin, try and market your solo ads in bigger publications, targeting at those with subscriber rates over 100,000 The costs can be expensive but the profits arising from it will be much greater assuming you have done your homework correctly2 Target Specifically Affiliate Product Related E-zinesAgain, purchase a few sponsor ads but this time in reputable E-zines to send those that are interested straight to a download page where they can get your free viral report which is, of course, not only related to your affiliate product, it is also embedded with your affiliate link to help generate sales for that product Print has the greatest credibility and you can photocopy it for those who did not see it Build relationships with editors, writers and reporters in the publications your prospects and clients are most likely to read - or respect Include these media contacts in your database and treat them like your best clients Keep them informed of changes in your business Meet them for lunch or coffee. Debt negotiation is yet another option How do you know which will work best for you It depends on your level of debt, your level of discipline, and your prospects for the futureSelf-HelpDeveloping a BudgetThe first step toward taking control of your financial situation is to do a realistic assessment of how much money you take in and how much money you spend Start by listing your income from all sources Then, list your "fixed" expenses those that are the same each month like mortgage payments or rent, car payments, and insurance premiums Remain extra careful as the the last thing you would want to do will be trigger harm to your ear by slipping and moving something into your ear canal The DVD series is extensive It includes a world music episode, which features sounds from diverse cultures from many continents Youngsters are encouraged to dance, sing and play exotic instruments, such as the Celtic harp from Ireland, maracas from Latin America and djembe drum from Africa The World Animal Adventure features numerous exotic animals from all seven continents Among them are Arctic snow monkeys, Australian kangaroos and Asian pandas.

    Reply
  • Branding is More Than Your Logo

    Posted by IngernDug on 03/22/2013 07:32am

    The title which is usually used as the hyper-linked text, should contain your important keywords It is good to work with ten different options of title and description as it not only gives you more room to play with several keywords, but it also search engines give you a wider keyword coverageWhen soliciting external links, it is better to provide your own cut and paste HTML code Webmasters like it when a ready to paste HTML code is available for them to use, to provide a link to your website Consider the following examples:"Website Promotion & Search Engine Optimization"SEO Rank provides Website promotion and Search Engine Optimization (SEO) services for small websites to large e-commerce sites requiring Search Engine Optimization & Ranking "Google PageRank & Link Popularity"Increase your Google PageRank (PR) and your website's Link Popularity through focused link building You may need to attend teleconferences, or travel to events, and these costs should be considered BEFORE you jump in to any easy home business with both feet 4 No Inventory to Maintain We've all seen the easy home business opportunity that lets you get in on their hot opportunity - if you'll fill your garage with products Those days are gone! In today's environment, easy home businesses do all the product handling for you - they will produce it, package it, ship it, and even bill the customer on your behalf Your only requirement is to tell them where to send your earnings! Be sure that the easy home business you choose has no inventory requirements 5. Do you enjoy making crafts Sell them online (be sure and mark up the price for shipping and handling) Do you enjoy writing Write a small booklet or how-to manual and sell it as an ebook Do you enjoy computer programming Write a program and sell through shareware groups or even thru your own affiliate program Just about anything you love doing can be magically transformed into a business opportunity for you After this you will be asked a series of questions that will help to ascertain what your likes and dislikes are The website will then process all of the information that you have provided, in confidence, and attempt to provide you with a list of potential people that you should get along with Once you have been given a shortlist of people that match the criteria that you have provided you have the opportunity to contact them or not, there is no obligation what so ever, so you will never feel pressured As everything is online you chat with the people that have been chosen for you by the dating site and then decide whether you would like to take the relationship any further If you are just looking for casual dating, then you will only ever be provided with people that are looking for the same thing.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Targeted attacks and advanced threats are customized to infiltrate your unique IT infrastructure, evade conventional defenses, and remain hidden while stealing your corporate data. To detect these criminal intrusions, analysts and security experts agree that organizations should deploy advanced threat protection as part of an expanded security monitoring strategy. For this comparative analysis of breach detection systems, product analysis reports and comparative analysis reports are used to create the security …

  • Not all enterprise applications are created equal. Sophisticated applications need developer support but other more basic apps do not. With the right tools, everyone is a potential app developer with ideas and a perspective to share. Trends such as low-code development and model driven development are fundamentally changing how and who creates applications. Is your organization ready? Read this report and learn: The seven personas of enterprise app delivery How application ownership is spreading to the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds