It is plausible that Trenčín Castle was founded during the Great Moravian era. In the beginning of the 11th century, the region was controlled by king Bolesław I the Brave of Poland. In 1017, Stephen I of Hungary conquered the region which remained part of Hungary until 1918. By the end of the 11th century, the castle became the administrative centre of Trencsén county in the Kingdom of Hungary. As one of the few stone castles in the country it resisted the disastrous invasion of Mongols in 1241. In 1263 Trenčín was in the possession of Jakab Cseszneky royal swordbearer, but in 1302 King Wenceslas I took it away from the Cseszneky brothers because they were supporting his rival Charles Robert, and donated it to Matthew III Csák. Between 1302 and 1321 the castle was the seat of the powerful magnate Matthew Csák who controlled most of what is now Slovakia. Challenging the authority of king Charles Robert, Matthew Csák maintained a large court and pursued his own foreign policy. The Treaty of Trentschin between Bohemia, Hungary, and Poland was signed in the city in 1335.