In 1841, Scott became the Commanding General of the United States Army, beating out his rival Edmund P. Gaines for the position. After the outbreak of the Mexican–American War in 1846, Scott was relegated to an administrative role, but in 1847 he led a campaign against the Mexican capital of Mexico City. After capturing the port city of Veracruz, he defeated Mexican General Antonio López de Santa Anna's armies at the Battles of Cerro Gordo, Contreras, and Churubusco. He then captured Mexico City, after which he maintained order in the Mexican capital and indirectly helped envoy Nicholas Trist negotiate the Treaty of Guadalupe Hidalgo, which brought an end to the war.